html通过xpath添加class,xpath如何通过class来定位元素

xpath中没有提供对class的原生查找方法。但是我在stackoverflow上看到了一个很有才的回答。现翻译如下

原帖链接(不管你能不能看到,总之原帖都是要贴的,要看到请自带天梯):

翻译如下

This selector should work but will be more efficient if you replace it with your suited markup:

这个表达式应该是可行的。不过如果你把class换成更好识别的标识执行效率会更高

//*[contains(@class, 'Test')]

But since this will also match cases like class="Testvalue" or class="newTest", @Tomalak's version provided in the comments is better:

但是这个表达式会把类似 class="Testvalue" 或者 class="newTest"也匹配出来。 @Tomalas 在评论里面的版本更好

//*[contains(concat(' ', @class, ' '), ' Test ')]

If you wished to be really certain that it will match correctly, you could also use the normalize-space function to clean up stray whitespace characters around the class name (as mentioned by @Terry):

如果你希望匹配的结果尽量精确,你还可以使用 normalize-space 功能来清除class名称周围的空格

//*[contains(concat(' ', normalize-space(@class), ' '), ' Test ')]

Note that in all these versions, the * should best be replaced by whatever element name you actually wish to match, unless you wish to search each and every element in the document for the given condition.

请注意在所有这些版本里,除非你想要在所有元素里搜索带有这些条件的元素,否则你最好把*号替换成你想要匹配的具体的元素名(标签名)。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值