您的位置:首页 > 其它

xpath如何通过class来定位元素

2016-08-11 06:35 344 查看
xpath中没有提供对class的原生查找方法。但是我在stackoverflow上看到了一个很有才的回答。现翻译如下
原帖链接(不管你能不能看到,总之原帖都是要贴的,要看到请自带天梯):
http://stackoverflow.com/questions/1604471/how-can-i-find-an-element-by-css-class-with-xpath

翻译如下
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.

请注意在所有这些版本里,除非你想要在所有元素里搜索带有这些条件的元素,否则你最好把*号替换成你想要匹配的具体的元素名(标签名)。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: