使用这样的 xpath 来查找 web 元素可以吗? [英] Is it okay to use such xpath to find web elements?

查看:26
本文介绍了使用这样的 xpath 来查找 web 元素可以吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑这个应该总是返回一个元素的 xpath.

//div[@id='MyDiv123']/div[contains(@class, 'super')]

假设我们不会再添加类为 super 的 div.鉴于这些信息,我认为使用 /div[contains(@class, 'super')] 不是一个好主意,因为如果 div[contains(@class, 'super')] 被放置在另一个元素中.

我们不应该使用 //div[contains(@class, 'super')] 代替吗?

解决方案

我不喜欢将 XPath 用于可以编写为 CSS 选择器的定位器.我认为它更简单

#MyDiv123 >div.super

或者只是

div.super

如果它在页面上是唯一的.

XPath contains() 是一个字符串匹配.下面的所有元素都将匹配您的 XPath 定位器,但它们都不匹配上面的 CSS 选择器.

<div class="superior" ...><div class="abcsuperdef" ...>

...你明白了...

Consider this xpath which should always return one element.

//div[@id='MyDiv123']/div[contains(@class, 'super')]

Assume that we won't add anymore divs whose class is super. Given that info, I don't think that it is a good idea to use /div[contains(@class, 'super')]because the xpath will break if div[contains(@class, 'super')] is placed inside another element.

Shouldn't we be using //div[contains(@class, 'super')] instead ?

解决方案

I don't like using XPaths for locators that can be written as a CSS selector. I think it's much simpler as

#MyDiv123 > div.super

or just

div.super

if it's unique on the page.

XPath contains() is a string match. All the elements below will match your XPath locator but none of them will match the CSS selectors above.

<div class="super-duper" ...>
<div class="superior" ...>
<div class="abcsuperdef" ...>

... you get the idea...

这篇关于使用这样的 xpath 来查找 web 元素可以吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆