我有一个列表网络元素,其中有一堆链接。 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/