【问题标题】:XPath to match @class value and element value?XPath 匹配@class 值和元素值?
【发布时间】:2013-10-21 20:07:14
【问题描述】:

我想定位这个元素,

<div class="item-price">$0.99</div>

使用 XPath 表示选择 class 属性等于 "item-price" 并且其内容包含美元符号 ($) 的元素。

【问题讨论】:

  • 某个属性与@attributename匹配,可以对内容使用contains()函数。您能否尽最大努力使用这 2 个?
  • 好的。 //div[@class="item-price" and contains("$")] 但我不确定如何进行连词。我也见过//div[one][theother]
  • 你看过documentation of contains()吗?你非常接近(contains(.,'$') 会这样做)

标签: html xml xpath


【解决方案1】:

这个 XPath 表达式:

//div[contains(@class, 'item-price') and contains(., '$')]

将匹配包含“$”的item-price 类的所有div 元素。

如果您想匹配在 @class 值中指定的多个 CSS 样式的情况,在 @class 的测试中使用 contains() 很有用。


警告:要获得更稳健的解决方案,请应用以下技术来避免意外的子字符串匹配(item-price 匹配,例如 item-prices):

//div[contains(concat(' ',@class,' '), ' item-price ') and contains(., '$')]

【讨论】:

  • 我喜欢你通过告诉我contains() 给我的心灵感应支持,因为它非常有价值。我更喜欢上面使用的连词语法。所以我很纠结选择哪个作为答案,因为两者都是正确的。
  • 欢迎您提供心灵感应支持。将近 5 年之后,也许您现在可以选择一个答案或另一个答案给accept? :-)
【解决方案2】:
//div[@class = 'item-price'][contains(., '$')]

【讨论】:

    【解决方案3】:

    根据 HTML:

    <div class="item-price">$0.99</div>
    

    有:

    • 类属性只有一个值,即item-price
    • innerText$ 符号开头。

    因此,要根据类属性的值定位此元素,即item-price 和以美元符号 ($) 开头的 innerText 内容,您可以使用以下任一解决方案:

    • 使用starts-with()

      //div[@class='item-price' and starts-with(., '$')]
      
    • 使用contains()

      //div[@class='item-price' and contains(., '$')]
      

    【讨论】:

      猜你喜欢
      • 2014-02-02
      • 2022-01-14
      • 2013-04-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多