【问题标题】:Where starts webdriver looking for elements using xpath从哪里开始 webdriver 使用 xpath 查找元素
【发布时间】:2019-05-12 21:57:30
【问题描述】:

我目前正在使用 Selenium/Webdriver 测试一个网站,该网站在几个框中显示人员的姓名和地址。例如,每个框都包含一个名字字段。所有这些字段都生成了ID,所以我不能使用它们。

我的方法是先找到盒子,然后再找到我要寻找的元素。我使用这样的 xPath 表达式,有点复杂,但对于问题,这种方式更容易

WebElement box3 = driver.findElement(By.xpath("//div[contains(@boxnum,'3')]");
WebElement firstName = box3.findElement(By.xpath(".//div[contains(@field,'firstname')]/input");

我也知道有绝对和相对 xPath 表达式,但显然我还没有真正理解它。如果我省略了在 xPath 中搜索 firstName 元素的前导点,则会找到第一个框中的名字字段。但是,我认为我不需要这个,因为我从“box3”开始搜索。不幸的是,我还没有找到以我理解的方式向我解释这一点的文档。我希望这里有人可以解释一下。

【问题讨论】:

  • 你能发布网址或至少相关的html吗?
  • 对不起,这是一个内网App
  • 您至少需要提供相关的 html 和您的预期输出,否则 OP 如何帮助您
  • 不要误会我的意思,但为什么需要 html?我的问题是,为什么第二个 xpath 表达式搜索整个 Dom,而不是仅使用从已经成功定位的元素“box3”开始的页面部分?

标签: selenium xpath webdriver


【解决方案1】:

不是真的。

鉴于以下代码针对 https://www.seleniumeasy.com/test/bootstrap-dual-list-box-demo.html 页面进行评估,如下所示:

driver.get("https://www.seleniumeasy.com/test/bootstrap-dual-list-box-demo.html");
WebElement listGroup = driver.findElement(By.xpath("//ul[@class='list-group']"));
List<WebElement> entries = listGroup.findElements(By.xpath("//li[@class='list-group-item']"));
entries.forEach(entry -> System.out.println(entry.getText()));

你会得到下一个输出:

bootstrap-duallist
Dapibus ac facilisis in
Morbi leo risus
Porta ac consectetur ac
Vestibulum at eros
Cras justo odio
Dapibus ac facilisis in
Morbi leo risus
Porta ac consectetur ac
Vestibulum at eros

因为 Selenium 从文档根计算 XPath

如果你将代码修改为:

driver.get("https://www.seleniumeasy.com/test/bootstrap-dual-list-box-demo.html");
WebElement listGroup = driver.findElement(By.xpath("//ul[@class='list-group']"));
List<WebElement> entries = listGroup.findElements(By.xpath(".//li[@class='list-group-item']"));
entries.forEach(entry -> System.out.println(entry.getText()));

您将仅从第一列获取值。

bootstrap-duallist
Dapibus ac facilisis in
Morbi leo risus
Porta ac consectetur ac
Vestibulum at eros

在第二种情况下,XPath 表达式仅应用于 当前节点

查看Selecting Nodes 章节:

参考资料:

【讨论】:

  • 感谢这个答案,非常详细!在阅读时,我想到了一个额外的问题。如果我的第二次搜索不是通过 xpath 会发生什么。如果我使用这样的东西,DOM 的哪一部分会被抓取: WebElement firstName = box3.findElement(By.className("xyz"));它会使用完整的 DOM,还是只使用从 box3 开始的部分?
猜你喜欢
  • 2021-03-31
  • 1970-01-01
  • 2011-04-14
  • 1970-01-01
  • 2023-03-18
  • 1970-01-01
  • 2018-08-28
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多