如何使用 XPath 通过 CSS 类查找元素? [英] How can I find an element by CSS class with XPath?

查看:31
本文介绍了如何使用 XPath 通过 CSS 类查找元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的网页中,有一个 div 和一个名为 Testclass.

In my webpage, there's a div with a class named Test.

如何使用 XPath 找到它?

推荐答案

这个选择器应该可以工作,但如果你用适合的标记替换它会更有效率:

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

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

或者,因为我们知道所寻找的元素是一个 div:

Or, since we know the sought element is a div:

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

但由于这也将匹配 class="Testvalue"class="newTest" 之类的情况,@Tomalak 在评论中提供的版本更好:

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

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

如果您真的希望确定它会正确匹配,您还可以使用 normalize-space 函数来清除类名周围的杂散空白字符(如@Terry 所述):

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):

//div[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.

这篇关于如何使用 XPath 通过 CSS 类查找元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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