python - 如何在python中解析html表
问题描述
我是解析表和正则表达式的新手,你能帮忙在 python 中解析这个吗:
<table callspacing="0" cellpadding="0">
<tbody><tr>
<td>1text 2text</td>
<td>3text </td>
</tr>
<tr>
<td>4text 5text</td>
<td>6text </td>
</tr>
</tbody></table>
我需要“3text”和“6text”
解决方案
您可以使用 CSS 选择器select()
并select_one()
获得“3text”和“6text”,如下所示:
import requests
from bs4 import BeautifulSoup
html_doc='''
<table callspacing="0" cellpadding="0">
<tbody><tr>
<td>1text 2text</td>
<td>3text </td>
</tr>
<tr>
<td>4text 5text</td>
<td>6text </td>
</tr>
</tbody></table>
'''
soup = BeautifulSoup(html_doc, 'lxml')
soup1 = soup.select('tr')
for i in soup1:
print(i.select_one('td:nth-child(2)').text)
您还可以使用find_all
方法:
trs = soup.find('table').find_all('tr')
for i in trs:
tds = i.find_all('td')
print(tds[1].text)
结果:
3text
6text
推荐阅读
- c - 如何使用 C 在运行时更改串行端口的波特率?
- javascript - 如何使用下拉列表中的值向数据库发送请求?
- c# - 访问克隆选项卡项中的控件
- java - 以分钟、秒、毫秒等形式确定瞬间的精度?
- jquery - jquery table2excel 删除文本并对齐?
- flutter - Flutter - Providers 和 Future 调用,如何共享同一个实例?
- javascript - 如何不清除输入字段中的先前输入。按钮类键盘
- pandas - 使用 to_csv() 时,Pandas Cell 数据被省略号截断
- solr - SOLR 加入 3 个流
- awk - 如何在长文本文件中的 grep 数字之前 grep N (7) 列行