如何通过CSS类和XPath找到一个元素? [英] How can I find an element by CSS class with XPath?

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

问题描述

在我的网页中,有一个名为Test的类。如何用XPath找到它?

In my webpage, there's a div with a class named Test. How can I find it with XPath?

推荐答案

这个选择器应该可以工作, :

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

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

或者,因为我们知道seek元素是 div

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

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

但是因为这也会匹配 class =Testvalue class =newTest code>,@注释中提供的@ 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.

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

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