2

假设我有一个这样的 html 表:

<table>
    <tr>
        <tr>...
        </tr>
        <tr>...
        </tr>
    </tr>
    <tr>
        <tr>...
        </tr>
        <tr>...
        </tr>
    </tr>
    ...
</table>

我可以找到表格标签。我怎么能找到第一层表格行是儿子..而不是表格的孙子。

print table.findAll('tr') # would return All the trs under table which is not what I want.
4

1 回答 1

2

尝试以下操作:

from bs4 import BeautifulSoup

soup = BeautifulSoup('''
<body>
    <table>
        <tr id="tr_1">
            <tr id="tr_1_1">..</tr>
            <tr id="tr_1_2">...</tr>
        </tr>
        <tr id="tr_2">
            <tr id="tr_2_1">...</tr>
            <tr id="tr_2_2">...</tr>
        </tr>
    </table>
</body>''', ['lxml','xml'])

for tr in soup.select('table > tr'):
    print(tr)
    print('---')

印刷

<tr id="tr_1">
<tr id="tr_1_1">..</tr>
<tr id="tr_1_2">...</tr>
</tr>
---
<tr id="tr_2">
<tr id="tr_2_1">...</tr>
<tr id="tr_2_2">...</tr>
</tr>
---

注意:需要lxml

于 2013-09-09T17:34:25.263 回答