javascript - Selenium xpath 问题

标签 javascript selenium selenium-webdriver web-scraping selenium-chromedriver

我在使用 selenium 和 xpath 时遇到一个非常奇怪的问题。我有一个呈现 25 <a> 的页面带有嵌套 <img/>标签。我需要使用 findElements()所有这些元素。如果我获取页面源代码并通过文本搜索以下子字符串:“alt="Expand List"”,我会得到 25 次出现。但是当我执行命令let items = await driver.findElements(By.xpath("//a[//img[contains(@alt,'Expand List')]]"))时我得到了 32 件元素。我在 google chrome 中记录了这些项目并添加到列表中 <a>包含具有不同 alt 值的图像。有任何想法吗?这段代码:

    let text = await driver.getPageSource();
    var count = (text.match(/alt="Expand List"/g) || []).length;
    let items = await driver.findElements(By.xpath("//a[//img[contains(@alt,'Expand List')]]"))
    console.log(count, items.length); //outputs 25, 32

enter image description here 这张图片的 alt Collapse List出现在<a>

enter image description here

最佳答案

你的 xpath 应该更像是:

//a/img[contains(@alt,'Expand List')]

一个斜杠表示它是父级 //a 的子级。

我强烈建议使用浏览器插件来测试 xpath。我几乎每天都使用 ChroPath。您还可以使用

之类的内容在 devtools 控制台中测试 xpath
$x('//a/img[contains(@alt,'Expand List')]')

将给出如下输出:

XPath in Devtools console

关于javascript - Selenium xpath 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60285505/

相关文章:

python - selenium - find_element_by_name 需要解释

ruby - 仅在先前的 Selenium 测试失败时才运行 Selenium 测试

selenium-webdriver - 无法使用 selenium webdriver 2.53.0 打开 Microsoft Edge 浏览器

javascript - "this"原型(prototype)内未定义

javascript - 关闭对象创建 : What are the advantages/disadvantages of these two approaches?

javascript - 位置没有被动画改变

java - Selenium 网络驱动程序 : How to call a class from selenium Junit program

c# - 验证 FQDN 的正则表达式

python - 填充用户名和密码时,selenium python 中的元素不难处理

python - 使用 Firefox WebDriver 单击与同名标签耦合的单选按钮