Skip to main content
 首页 » 编程设计

python之使用 BeautifulSoup 只读取外表的行

2024年10月24日13yjmyzz

  <table> 
  <tbody> 
    <tr> 
        <td>Some Content </td> 
        <td>Some Content </td> 
    </tr> 
    <tr> 
        <td>Some Content </td> 
        <td>Some Content </td> 
    </tr> 
    <tr> 
        <table> 
            <tbody> 
                <tr> 
                    <td>Some Content </td> 
                    <td>Some Content </td> 
                </tr> 
                <tr> 
                    <td>Some Content </td> 
                    <td>Some Content </td> 
                </tr> 
                <tr> 
                    <td>Some Content </td> 
                    <td>Some Content </td> 
                </tr> 
            </tbody> 
        </table> 
    </tr> 
  </tbody> 
<table> 

我有一些 HTML 和上面的表格内容。在一张 table 旁边还有一些 table 。

当我使用 beautifulsoup 阅读 tr 时

table_grid_1 = soup.find("table", {"id": "GridView1"}) 
rows = table_grid_1.find("tbody").find_all("tr") 

内表的行也被读取。

i.e `print "length " + str(len(rows))` prints 5. but I want to read tr of only outer table like size should be 3 

如何只读取外表的行?

请您参考如下方法:

您可以使用 recursive=False parameter 来实现这一点如下:

soup = BeautifulSoup(html) 
table_grid_1 = soup.find("table", {"id": "GridView1"}) 
rows = table_grid_1.find("tbody").find_all("tr",recursive=False) 
print len(rows) 

返回 3。