python - 使用 Python 和 Selenium 为什么我无法通过链接文本找到链接?

标签 python selenium selenium-webdriver

我有一个列表网络元素,其中有一堆链接。 html 看起来像:

<li>
<a href="/shopping/cart_items/12444" data-method="delete" rel="nofollow" class="ss-delete"><span class="ss-icon"></span> Remove</a>
<a href="/sessions/new"><span class="ss-icon"></span> Sign in to save items</a
...

当我尝试做类似的事情时:

link = element.find_element_by_link_text('Sign in to save items')

我收到一条错误消息:

NoSuchElementException: Message: Unable to locate element: {"method":"link text","selector":"Sign in to save items"}

我已经能够通过执行 find_elements_by_tag_name('a') 然后仅使用具有正确 HREF 的链接来找到此链接,但我想了解为什么第一种方法失败。

最佳答案

我之前就遇到过 find_element_by_link_text 方法有时有效有时无效;即使在单个案例中。我认为这不是访问元素的可靠方法;最好的方法是使用 find_element_by_id

但就你的情况而言,当我访问该页面时,没有 id 可以帮助你。您仍然可以通过两种方式尝试 find_elements_by_xpath:

1- 访问标题:find_element_by_xpath["//a[contains(@title = '登录以保存项目')]"]

2- 访问文本:find_element_by_xpath["//a[contains(text(), '登录以保存项目')]"]

希望有帮助。

关于python - 使用 Python 和 Selenium 为什么我无法通过链接文本找到链接?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31453312/

相关文章:

python - 使用 Python 循环遍历文件时如何提前读取文件?

Python数组解包报错: need more than 3 values

python - 使用 sklearn.feature_extraction.text.TfidfVectorizer 的 tf-idf 特征权重

java - Selenium 获取 Twingly 的文本输入(Java 代码)

java - 在chrome不弹出窗口的情况下更改下载目录

java - 如何使用 FirefoxDriver 对象使用 waitForCondition() 函数?

java - 如何处理使用 Web Driver 动态生成值的表?

python - 使用变量访问另一个变量

java - 如何在 Java 中使用 Selenium 获取 div 内的 anchor 标记 href 和 anchor 标记文本

Python Selenium 数组