【问题标题】:XPath select all but not self::strong and self::strong/following-sibling::text()XPath 选择所有但不是 self::strong 和 self::strong/following-sibling::text()
【发布时间】:2013-08-31 04:00:59
【问题描述】:

所以我有以下示例 html 来解析。

<div>
    <strong>Title:</strong>
    Sub Editor at NEWS ABC

    <strong>Name:</strong>
    John

    <strong>Where:</strong>
    Everywhere

    <strong>When:</strong>
    Anytime

    <strong>Everything can go down there..</strong>

    Lorem Ipsum blah blah blah....
</div>

我想提取整个 div,但我不希望 Title 和 Where 和 When 带有以下值。

到目前为止,我已经测试了以下 XPath。

a) 没有跟随兄弟(1:不工作。2:工作)

1. //div/node()[not(strong[contains(text(), "Title")])]

2. //div/node()[not(self::strong and contains(text(), "Title"))]

a) 有以下兄弟姐妹(1:不工作。2:不工作)

1. //div/node()[not(strong[contains(text(), "Title")]) and not(strong[contains(text(), "Title")]/following-sibling::text())]

2. //div/node()[not(self::strong and contains(text(), "Title") and following-sibling::text())]

如何实现我的追求?

【问题讨论】:

  • 你能帮我说一下你想要提取的值是什么,什么不是......不太清楚......
  • 我想删除强元素及其后面的文字,方法是说强元素是否包含一些文本(例如标题)。
  • &lt;strong&gt;Name:&lt;/strong&gt; John 然后也需要删除——对吧?
  • 可能是也可能不是。这个想法是编写一个选择器,可以删除任何提供其内容的强元素。
  • 非常非常好的问题确实..+1..虽然xpath只能根据需要选择节点,但不能删除任何东西......

标签: python xpath


【解决方案1】:

我认为以下内容符合您想要做的 - 它不包括包含标题的强元素以及它之后的文本节点。您可以扩展它以包含您想要排除的其他强元素:

//div/node()[not(self::strong and contains(text(), "Title") or preceding-sibling::strong[1][contains(text(), "Title")])]

强节点被跳过:

not(self::strong and contains(text(), "Title")

以下文本被跳过:

preceding-sibling::strong[1][contains(text(), "Title")]

请注意,文本节点需要检查其最近的前同级(而不是其后同级)。

【讨论】:

  • 所以你的意思是“删除所有包含前兄弟中给定文本的元素”这很好!它还会“只删除名为 strong 的元素”吗?
  • 这里的xpath中,会移除带有文本“Title”的强节点。我是否误读了您的要求,您是否要删除所有强元素?
  • 我想删除 strong 及其以下文字。
  • 是的,这个 xpath 确实做到了。
  • //div/node()[not(self::strong and contains(text(), "Title") 或前面的兄弟姐妹::strong[1][contains(text(), "标题")])]
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-02-13
  • 2018-06-15
  • 2023-03-21
  • 1970-01-01
  • 1970-01-01
  • 2012-01-19
相关资源
最近更新 更多