简体   繁体   English

具有特定值的任何属性的所有元素的 XPath?

[英]XPath for all elements with any attribute with specific value?

I am using Selenium to identify any HTML element that may have a specified value in any of its attributes.我正在使用 Selenium 来识别任何可能在其任何属性中具有指定值的 HTML 元素。 I was hoping that there would be some way in XPath to do this, but I haven't been able to find any answers yet.我希望在 XPath 中有一些方法可以做到这一点,但我还没有找到任何答案。

First, you have to transform HTML into xhtml if you want to apply xpath selections on it.首先,如果要对其应用 xpath 选择,则必须将 HTML 转换为 xhtml。

The xpath for selecting an (x)html element having a specified value in one of its attributes is:选择在其属性之一中具有指定值的 (x)html 元素的 xpath 是:

//*[@*="specified value"]

Here are XPath expressions for selecting...以下是用于选择的 XPath 表达式...

  • All elements :所有元素

     //*
  • All elements with an attribute, a :所有具有属性a元素:

     //*[@a]
  • All elements with an attribute a equal to v :属性a等于v的所有元素:

     //*[@a='v']
  • All elements with any attribute:具有任何属性的所有元素:

     //*[@*]
  • All elements with any attribute equal to v :任何属性等于v的所有元素:

     //*[@*='v']

Credit to @Pierre for first posting //*[@*='v'] .感谢@Pierre第一次发布//*[@*='v']

//*[@*[contains(.,'val')]]将从根中找到任何其值中包含'val'的属性的任何后代节点。

Thanks Guys!!多谢你们!! I tried this on XPathFiddle and it seems to work:我在 XPathFiddle 上试过这个,它似乎工作:

Sample HTML :示例 HTML

<html>
  <body>
    <div my-attr1='value1'>
        <a>  
            <span my-attr2='value2'> Some Link </span>
        </a>
    </div>
    <span my-attr3='value1'> Some Text </span>
  </body>
</html>

Sample XPath : html//*[@*='value1']示例 XPathhtml//*[@*='value1']

The XPath above, selects the div with my-attr1 and the span with my-attr3 .上面的 XPath 使用my-attr1选择div ,使用my-attr3选择span

//a[@href[contains(.,'mailto:')]]
此路径将找到所有带有 href 属性的标签都包含“mailto:”字符串

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM