【发布时间】:2016-08-10 09:35:26
【问题描述】:
我有一个包含嵌套表的 html。我希望在外部表格和内部表格之间找到文本。我认为这是一个经典的问题,但到目前为止还没有找到答案。我想出的是
tree.xpath(//p[not(ancestor-or-self::table)])。但这不起作用,而是因为所有文本都来自外部表格。也只使用preceding::table 是不够的,因为文本可以包围内表。
举个概念性的例子,如果一个表格看起来像 [...text1...[inside table No.1]...text2...[inside table No.2]...text3...],我怎样才能得到 text1/2/3 而不会被来自 inside tables No.1&2 的文本污染。也许这是我的想法,是否可以通过 xpath 构建一个 table layer 的概念,这样我就可以告诉 lxml 或其他库“Give me all text between layer 0 and 1”
下面是一个简化的示例 html 文件。实际上,外部表可能包含许多嵌套表,但我只想要最外部表与其第一个嵌套表之间的文本。谢谢各位!
<table>
<tr><td>
<p> text I want </p>
<div> they can be in different types of nodes </div>
<table>
<tr><td><p> unwanted text </p></td></tr>
<tr><td>
<table>
<tr><td><u> unwanted text</u></td></tr>
</table>
</td></tr>
</table>
<p> text I also want </p>
<div> as long as they're inside the root table and outside the first-level inside tables </div>
</td></tr>
<tr><td>
<u> they can be between the first-level inside tables </u>
<table>
</table>
</td></tr>
</table>
它返回["text I want", "they can be in different types of nodes", "text I also want", "as long as they're inside the root table and outside the first-level inside tables", "they can be between the first-level inside tables"]。
【问题讨论】: