如何使用xpath从父html检索嵌套和非嵌套子项?

2024-10-01 22:41:14 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在使用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以直接在父级中显示所有内容,包括字符串


Tags: 字符串brdivherenoth4filteredclass
1条回答
网友
1楼 · 发布于 2024-10-01 22:41:14

几乎正确。在这里:

//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")
]

相关问题 更多 >

    热门问题