如何使用 XPath 通过 CSS 类查找元素?

编程入门 行业动态 更新时间:2024-10-24 14:26:08
本文介绍了如何使用 XPath 通过 CSS 类查找元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

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

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 类查找元素?

本文发布于:2023-10-08 02:41:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1471273.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:如何使用   元素   XPath   CSS

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!