python如何获取tbody下tr元素个数
时间: 2023-05-30 22:07:07 浏览: 333
可以使用BeautifulSoup库来解析HTML文档,然后通过find_all方法找到tbody标签,再通过len方法获取其中tr元素的个数。示例代码如下:
```python
from bs4 import BeautifulSoup
html = '''
<table>
<thead>
<tr>
<th>Header 1</th>
<th>Header 2</th>
<th>Header 3</th>
</tr>
</thead>
<tbody>
<tr>
<td>Row 1, Column 1</td>
<td>Row 1, Column 2</td>
<td>Row 1, Column 3</td>
</tr>
<tr>
<td>Row 2, Column 1</td>
<td>Row 2, Column 2</td>
<td>Row 2, Column 3</td>
</tr>
<tr>
<td>Row 3, Column 1</td>
<td>Row 3, Column 2</td>
<td>Row 3, Column 3</td>
</tr>
</tbody>
</table>
'''
soup = BeautifulSoup(html, 'html.parser')
tbody = soup.find('tbody')
tr_count = len(tbody.find_all('tr'))
print(tr_count) # 输出3
```