18910140161

Python-如何在BeautifulSoup中获取嵌套标记的所有元素?-堆栈溢出

顺晟科技

2022-10-19 13:13:06

244

我对HTML和解析非常陌生,所以如果我使用了错误的术语,我很抱歉。我之前问过一个类似的问题,并找到了一些有用的答案。下面的HTML代码片段包含两个表和两个表头(以及更多行,但与本文无关)

<body>
    <table>
        <tr class="header">
            <th><strong>Heading 1</strong></th>
            <th><strong>Heading 2</strong></th>
            <th><strong>Heading 3</strong></th>
            <th><p><strong>Heading 4, line 1</strong></p>
            <p><strong>Heading 4, line 2</strong></p></th>
        </tr>

        <tr>
            <!--Many more rows-->>
        </tr>
    </table>

    <table>
        <tr class="header">
            <th><strong>Diff Header 1</strong></th>
            <th><strong>Diff Header 2</strong></th>
            <th><strong>Diff Header 3</strong></th>
            <th><p><strong>Diff Header 4, line 1</strong></p>
            <p><strong>Diff Header 4, line 2</strong></p></th>
        </tr>
    
        <tr>
            <!--Many more rows-->>
        </tr>
    </table>
</body>

我正在尝试使用Python3.6和BeautifulSoup4来解析它,并将文本提取到a列表中。我的问题是,我希望每个块都有单独的列表。我当前的代码似乎搜索并找到了所有标记,而不是第一个表中的标记。

以下是我所拥有的:

<body>
    <table>
        <tr class="header">
            <th><strong>Heading 1</strong></th>
            <th><strong>Heading 2</strong></th>
            <th><strong>Heading 3</strong></th>
            <th><p><strong>Heading 4, line 1</strong></p>
            <p><strong>Heading 4, line 2</strong></p></th>
        </tr>

        <tr>
            <!--Many more rows-->>
        </tr>
    </table>

    <table>
        <tr class="header">
            <th><strong>Diff Header 1</strong></th>
            <th><strong>Diff Header 2</strong></th>
            <th><strong>Diff Header 3</strong></th>
            <th><p><strong>Diff Header 4, line 1</strong></p>
            <p><strong>Diff Header 4, line 2</strong></p></th>
        </tr>
    
        <tr>
            <!--Many more rows-->>
        </tr>
    </table>
</body>

问题:如何修改此代码,使其只查找当前行中的标记,而不是每行中的标记?

谢谢您的帮助!


顺晟科技:

使用代替。

如果您的HTML片段来自问题:

打印:

  • TAG:
相关文章
我们已经准备好了,你呢?
2024我们与您携手共赢,为您的企业形象保驾护航