【问题标题】:How can i retrieve both nested and nonnested children from parent html using xpath?如何使用 xpath 从父 html 中检索嵌套和非嵌套子级?
【发布时间】:2017-05-18 13:37:48
【问题描述】:

我正在使用 python 创建一个网络爬虫。正在解析的 html 似乎有一些直接在父标记中的字符串,如下所示:

<div class="chapter-content3">
<noscript>...stuff here filtered successfully</noscript>
<center>...stuff here filtered successfully</center>
<h4>..stuff here shows</h4>
<p>...stuff here shows</h4>
<br>
"this stuff here doesnt show"
<br>
"this neither"
 <p>..stuff here shows</p>
 </div>

我的 xpath 是这样的:

//div[@class="chapter-content3"]/*[not(self::noscript) and not(self::center) and not(@class="row")]

这会调出所有内容,但不会直接在里面显示字符串

我应该如何构造 xpath 以直接在父级中显示包括字符串在内的所有内容

【问题讨论】:

  • 你想拥有所有的 xpath 吗?
  • @Edwin 至于结果 html 与输入 html 的顺序相同。任何解决方案都可以

标签: python html xml xpath


【解决方案1】:

几乎正确。这里:

//div[@class="chapter-content3"]/*[
   not(self::noscript) and not(self::center) and not(@class="row")
]

* 只选择实际元素。您要选择所有节点,即

//div[@class="chapter-content3"]//node()[
   not(self::noscript) and not(self::center) and not(@class="row")
]

或者,短一点

//div[@class="chapter-content3"]//node()[
   not(self::noscript or self::center or @class="row")
]

或者,一种不同的思考方式 - 除了祖先错误的所有文本节点:

//div[@class="chapter-content3"]//text()[
   not(ancestor::noscript or ancestor::center or ancestor::*/@class="row")
]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-12-23
    • 2020-02-25
    • 1970-01-01
    • 1970-01-01
    • 2020-10-01
    • 2014-03-11
    • 1970-01-01
    相关资源
    最近更新 更多