可以使用BeautifulSoup库来
解析
HT
ML
并提取表格数据。具体步骤如下:
安装BeautifulSoup库
pip install beautifulsoup4
导入所需库并读取HTML文件
from bs4 import BeautifulSoup
with open('file.html') as file:
soup = BeautifulSoup(file, 'html.parser')
使用find或findAll方法找到包含表格数据的div元素。假设该表格的所有行都存储在class为"row"的div中。
rows = soup.findAll('div', {'class': 'row'})
针对每行数据,使用find或findAll方法找到其包含的单元格元素并提取文本信息。
for row in rows:
cells = row.findAll('div', {'class': 'cell'})
row_data = []
for cell in cells:
row_data.append(cell.text)
print(row_data)
这样就可以提取出每行数据,并以列表形式存储其中的每个单元格数据。
完整代码示例:
from bs4 import BeautifulSoup
with open('file.html') as file:
soup = BeautifulSoup(file, 'html.parser')
rows = soup.findAll('div', {'class': 'row'})
for row in rows:
cells = row.findAll('div', {'class': 'cell'})
row_data = []
for cell in cells:
row_data.append(cell.text)
print(row_data)