所以基本上我正在嘗試用 Python 抓取一個網頁,但我被困在使用 BeautifulSoup 查找串列中一個元素的子元素的數量上,串列的 HTML 如下所示:
<table id="MyTable">
<thead>
<tr>...</tr>
</thead>
<tfoot>
<tr>...</tr>
</tfoot>
<tbody>
<tr>...</tr>
<tr>...</tr>
<tr>...</tr>
<tr>...</tr>
<tr>...</tr>
<tr>...</tr>
<tr>...</tr>
</tbody>
</table>
在我的情況下,我想獲取tr內部 tag的數量tbody,但由于它沒有 id,我發現沒有辦法用湯來獲取它,然后做一個findAll("tr"). 很確定這應該很容易,但找不到方法,我該怎么做?
uj5u.com熱心網友回復:
您可以通過選擇所有來檢查len()您的:resultSet<tr><tbody>
len(soup.select('#MyTable > tbody tr'))
例子
from bs4 import BeautifulSoup
html='''
<table id="MyTable">
<thead>
<tr>...</tr>
</thead>
<tfoot>
<tr>...</tr>
</tfoot>
<tbody>
<tr>...</tr>
<tr>...</tr>
<tr>...</tr>
<tr>...</tr>
<tr>...</tr>
<tr>...</tr>
<tr>...</tr>
</tbody>
</table>
'''
soup = BeautifulSoup(html)
len(soup.select('#MyTable > tbody tr'))
輸出
7
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/528632.html
上一篇:使用seleniumwebdriver僅獲取頁面源的一部分
下一篇:如何跳過bs4標簽內的一些迭代?
