【问题标题】:lxml xpath get text between two nested tableslxml xpath 获取两个嵌套表之间的文本
【发布时间】: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"]

【问题讨论】:

    标签: python xpath nested lxml


    【解决方案1】:

    如果最外面的表是根元素,则可以执行此操作的 XPath 之一:

    /table/descendant::table[1]/preceding::p
    

    在这里,您遍历最外层table 的第一个后代table,然后选择其前面的所有p 元素。

    如果没有,您将不得不采取不同的方法来访问tables 之间的p 元素,可能是使用generate-id() 函数。

    【讨论】:

    • 是的,外部表是根。这是我唯一确定的事情。如果文本不在

      中,它会起作用吗,实际上它们可以在

      中...我的文件有些混乱
    • @Skywalker326,您应该将信息添加到您的问题中
    • @Skywalker326 如果你只想要文本节点,你可以在 xpath 中使用 preceding::text() 代替更具体的遍历,例如 preceding::div/text() 等。
    • @LingamurthyCS 是的,我现在正在使用这个表达式。但恐怕我只是在 50+ html 文件上测试了它,而总共有 100K 文件。我怀疑会有文本围绕内部表格的情况,在这种情况下,前面将不起作用。例如,如果一个表看起来像这样 [...text1...[inside table No.1]...text2...[inside table No.2]...text3...],我怎样才能得到仅 text1/2/3 不会被表 1 和 2 中的文本污染。是否可以通过xpath建立一个table layer的概念,所以我可以表达“Give me all text between layer 0 and 1”。
    • @Skywalker326 您能否添加一个示例输入并告诉我们所需的输出。
    猜你喜欢
    相关资源
    最近更新 更多
    热门标签