【问题标题】:Select text immediately after font awesome icons using XPath使用 XPath 在字体真棒图标之后立即选择文本
【发布时间】:2020-05-10 14:54:28
【问题描述】:

我正在尝试提取未嵌套在 HTML 元素中的文本。这是HTML

<div class="col-sm-12">
  <i class='fa fa-map-marker'></i>theCity
  <i class='fa fa-link'></i>theEmail
  <i class='fa fa-phone'></i>thePhone1
  <i class='fa fa-phone'></i>thePhone2
  <b>Fax:</b>theFax
  <b>Address:</b>theAddress
</div>

我想得到以下结果

  • 城市
  • 电子邮件
  • 电话1
  • 电话2
  • 传真
  • 地址

如您所见,有不同的格式。 theCity、theEmail、thePhone1 和 thePhone2 具有相似的格式,而 theFax 和 theAddress 具有另一种格式。 我尝试使用以下语句获取这两种类型的数据,但没有成功。

这是我尝试的传真和地址的代码

//b/following-sibling::text()[1]

这是城市、电子邮件和电话数据类型的代码

normalize-space(//div[@class="fa-map-marker"]/following-sibling::text())

我做错了什么?

【问题讨论】:

    标签: html xml xpath xpath-2.0 xpath-1.0


    【解决方案1】:

    我做错了什么?

    1. 对于基于i 的标签,请注意fa fa-map-marker 类位于i,而不是div。此外,如果您希望使用相等,则必须针对整个属性值进行测试。如果您希望使用contains() 获得更强大的解决方案,请参阅XPath to match @class value and element value? 最后,不要忘记[1] 以确保您只获得紧随其后的文本节点。
    2. 对于基于b 的标签,请在使用following-sibling:: 之前指定b 元素的内容,因为您已经正确执行了。

    以下是用于选择每个目标的 XPath 表达式:

    • 城市//i[@class="fa fa-map-marker"]/following-sibling::text()[1]
    • 电子邮件//i[@class="fa fa-link"]/following-sibling::text()[1]
    • thePhone1//i[@class="fa fa-phone"][1]/following-sibling::text()[1]
    • thePhone2//i[@class="fa fa-phone"][2]/following-sibling::text()[1]
    • 传真//b[.="Fax:"]/following-sibling::text()[1]
    • 地址//b[.="Address:"]/following-sibling::text()[1]

    【讨论】:

    • 谢谢,您的回答完美。但我想知道的一件事是,如果我想通过 id 提及父 div 来引用 fa fa.... 类和基于 b 的标签怎么办。如果我们假设 col-md-12 上方还有另一个 div 嵌套了上面列出的所有 id 为“theList”的 div。我们如何将其纳入您的答案中。
    • 会像 //div[@id="theList"]//i[@class="fa fa-map-marker"]/following-sibling::text()[1]工作
    • 是的,以这种方式指定 ib 元素的继承是缩小范围的好方法。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-03
    • 1970-01-01
    • 1970-01-01
    • 2014-01-16
    相关资源
    最近更新 更多