英文:
Unable to click on a "text" link in google search page
问题
我正试图点击 Google 搜索页面上的新闻链接,HTML 结构如下图所示:
我尝试了以下的 XPath,但都没有生效:
//a/child::span[1][contains(.,'News')]
以下的 XPath 导致了无效的选择器:XPath 表达式“//a/child::span/following-sibling::text()[contains(.,'News')]”的结果是:[object Text]。它应该是一个元素。
//a/child::span/following-sibling::text()[contains(.,'News')]
谢谢
英文:
I am trying to click on News link on google search page the HTML structure looks like this
I tried following xpaths but none worked
//a/child::span[1][contains(.,'News')]
The following xpath resulted in invalid selector: The result of the xpath expression "//a/child::span/following-sibling::text()[contains(.,'News')]" is: [object Text]. It should be an element.
//a/child::span/following-sibling::text()[contains(.,'News')]
Thanks
答案1
得分: 1
//a[contains(.,'News')]
可能会返回此链接,但可能会返回一个包含多个元素的列表,您需要处理并从中选择正确的元素。
您可以使用Selenium的SearchContext来指定容器元素,或者使用xpath一行代码来解决,例如://div[@role='navigation']//a[contains(.,'News')]
(实际上在搜索包含'News'的链接时会在html树的某个位置搜索,在具有属性值为'navigation'的div内部搜索)。
英文:
//a[contains(.,'News')]
might return this link, but may result in a list of more than one element that you'd need to handle and select the right element from.
You can use Selenium's SearchContext to specify a container element, or solve it using an xpath one-liner like: //div[@role='navigation']//a[contains(.,'News')]
(Effectively searching for a link that contains 'News' somewhere in it's html-tree, somewhere inside a div that has a role attribute with value 'navigation').
答案2
得分: -1
你只需
//a[contains(., "新闻")]
请注意,"新闻"
不是 span
的一部分,而是 a
的一部分,所以你的第一个XPath不会起作用。
英文:
You simply need
//a[contains(., "News")]
Note that "News"
is not a part of span
, but a
, so your 1st XPath won't work
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论