下面是我的代码
public void someTest() {
String x = "/html/body/div/div["
String y = "]/a"
for (int i = 1; i < 5; i++){
String links = x + i + y;
driver.findElement(By.xpath(links)).click(); // This will iteratively go to the next link and click on it
}
}然而,我试图实现的是,一旦它点击了链接,它就应该寻找后代链接,并同时点击这些链接。那么有没有办法做到这一点呢?如果我尝试下面这样的方法,会起作用吗?
driver.findElement(By.xpath(links/descendant::a).click(); 发布于 2013-08-07 00:15:01
这是一种脆弱的编码方式,会在循环过程中更改xpath。相反,我建议使用findElements方法并遍历它返回的元素,如下所示:
public void someTest() {
xpath xpath_findlinks = "/html/body/div/div/a";
xpath relative_xpath = "./..//a";
for (WebElement eachlink : driver.findElements(By.xpath(xpath_findlinks))) {
eachlink.click();
for (WebElement descendantlink : eachlink.FindElements(By.xpath(relative_xpath))) {
descendantlink.click();
}
}
}请注意一个重要的区别。第一次调用findElements时,它在驱动程序上,所以它会遍历整个html;但第二次调用时,它是作为特定元素(当前链接)的方法调用的,所以您可以使用它来查找与该链接相关的元素-例如,查找后代元素。
我推荐使用这种结构;但是,如果不知道整个html,就很难知道要使用什么相对xpath。我提供的示例只是相对xpath的一个示例,其中包含./的独特开头。
发布于 2013-07-18 04:15:46
尝尝这个
String x = "/html/body/div/div[";
String y = "]//a"; // notice the double "//"XPath中的//应该整理a类型的所有子类型。
发布于 2013-07-18 12:47:30
您可能需要下面这样的逻辑
//点击links下a类型的后代
driver.findElement(By.xpath(links)).findElement(By.xpath("//a")).click();https://stackoverflow.com/questions/17709241
复制相似问题