使用 xpath 和 Selenium 选择元素
我的 HTML 看起来基本上如下所示:
...
<a class="btnX btnSelectedBG" href="#"><span>Sign in</span></a>
...
The following xpath in Selenium failed to find an element:
//a[contains(text(), 'Sign in') and contains(@class,'btnX')]
The following xpaths in Selenium success, but are not certain for me.
//a[contains(text(), 'Sign in')]
//a[contains(@class, 'btnX')]
为什么 xpath 找不到元素,我该怎么做才能让它工作?
I have HTML which looks basically like the following:
...
<a class="btnX btnSelectedBG" href="#"><span>Sign in</span></a>
...
The following xpath in Selenium fails to find an element:
//a[contains(text(), 'Sign in') and contains(@class,'btnX')]
The following xpaths in Selenium succeed, but are not specific enough for me.
//a[contains(text(), 'Sign in')]
//a[contains(@class, 'btnX')]
Why is the xpath failing to find an element, and what can I do to get it to work?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
匹配
Sign in
是a
的直接子元素或另一个元素的子元素的情况:我的意思是
;登录
并
登录在
Match cases where
Sign in
is directly child ofa
or child of another element:I mean
<a class="btnX btnSelectedBG" href="#">Sign in</a>
and
<a class="btnX btnSelectedBG" href="#"><b>Sign in</b></a>
//a[contains(@class,'btnX') and span[text()='Sign in']] 不是一个好主意,因为您将在 DOM 中搜索每个锚点,然后尝试将其与您的搜索条件。
理想情况下,您希望将 XPath 设置为具有 ID 的第一个上升元素,然后沿树向下移动。
例如,如果你的 html 是
你可以使用:
不幸的是,我不知道页面结构的其余部分,所以我不能给你比:更具体的东西,
但它确实不是一个很好的xpath。
(我的 XPath 看起来与您略有不同,因为我使用 . 作为 text() 的快捷方式,使用第二组 [] 作为 and 的快捷方式)
//a[contains(@class,'btnX') and span[text()='Sign in']] is not a good idea because you are going to search through the DOM for every anchor and then try and compary it to your search criteria.
You ideally want to key your XPath to the first ascendant element that has an ID and then work your way down the tree.
e.g. if your html is
You could use:
Unfortunatly I don't know the rest of the structure of the page so I can't give you anything more concrete than:
but it is really not a very nice xpath.
(My XPath's look slightly different to you because I have used . as a shortcut for text() and a second set of [] as a shortcut for and)
对我来说是啊。我认为这是最好的答案,但也欢迎其他解决方案!
Yaaa for me. I think this is the best answer, but open to other solutions!
对于操作来说,以下几点很重要。
“and”区分大小写,不应使用大写“AND”。
语法:
//tag[XPath Statement-1 and XPath Statement-2]
在这里您还可以找到许多其他在 Selenium 中查找 Xpath 的方法:https://www.swtestacademy.com/xpath-selenium/
For and operation the below point is important.
“and” is case-sensitive, you should not use the capital “AND”.
Syntax:
//tag[XPath Statement-1 and XPath Statement-2]
Here you can also find many other ways to find Xpath in Selenium: https://www.swtestacademy.com/xpath-selenium/