限制 WebDriver 范围未按预期工作

Limiting WebDriver scope is not working as expected

谁能解释一下为什么 data.size() 会变成 13,为什么 data1.size() 会变成 364?

根据我的理解,data.size() 应该是 0,因为 <td> 不是有效的 xpath 表达式,data1.size() 应该是 13,因为有 13 个 <td> 标签 inside/under降水元素。 364实际上是特定网页中“td”标签的总数。

System.setProperty("webdriver.chrome.driver", "C:\Program Files\Java\chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.manage().window().maximize();
driver.get("https://en.wikipedia.org/wiki/York");
Actions a = new Actions(driver);
WebElement precipitation = driver.findElement(By.xpath("//a[@title='Precipitation']//ancestor::tr"));
a.moveToElement(precipitation).build().perform();
List<WebElement> data = precipitation.findElements(By.xpath("td"));
List<WebElement> data1 = precipitation.findElements(By.xpath("//td"));
List<WebElement> data2 = precipitation.findElements(By.tagName("td"));
List<WebElement> data3 = precipitation.findElements(By.cssSelector("td"));
List<WebElement> data4 = driver.findElements(By.cssSelector("td"));
List<WebElement> data5 = driver.findElements(By.xpath("td"));
List<WebElement> data6 = driver.findElements(By.xpath("abcxyz"));
System.out.println("data = " +data.size());
System.out.println("data1 = " +data1.size());
System.out.println("data2 = " +data2.size());
System.out.println("data3 = " +data3.size());
System.out.println("data4 = " +data4.size());
System.out.println("data5 = " +data5.size());
System.out.println("data6 = " +data6.size());
driver.close();

实际上 "td" 是一个有效的表达式,它选择节点名称为 td 的节点,并且由于您没有使用 ///,因此搜索不会t 从 DOM 层次结构中的更高元素开始。这意味着

precipitation.findElements(By.xpath("td"));

相当于

driver.findElement(By.xpath("//a[@title='Precipitation']//ancestor::tr/td"));

// 将定位 DOM 中的所有匹配元素,即所有 <td> 节点。如果您想使用 precipitation 作为根节点并从那里开始搜索,您需要为当前上下文添加 .

precipitation.findElements(By.xpath(".//td"));

对于 <tr> 下的所有 <td>

precipitation.findElements(By.xpath("./td"));

<tr>

的直系子代

参考XPath Syntax

选择节点

XPath 使用路径表达式指向 XML 文档中的 select 个节点。该节点在以下语义的帮助下 select 编辑:

所以根据上面的讨论,一旦你确定了 webElement precipitation

WebElement precipitation = driver.findElement(By.xpath("//a[@title='Precipitation']//ancestor::tr"));

接下来获取后代 <td> 标签而不是:

List<WebElement> data = precipitation.findElements(By.xpath("td"));

根据上面的讨论,以最有效的方式识别所需的后代 <td> 元素,您需要附加 / 字符来表示从哪个节点开始搜索。

如此有效,您的代码行将是:

List<WebElement> data = precipitation.findElements(By.xpath(".//td"));

在一行中:

List<WebElement> data = precipitation.findElements(By.xpath("//a[@title='Precipitation']//ancestor::tr//td"));

这将 select 为您提供正确的 13 个所需的 <td> 个节点。