由于实验设备导出的数据为 html 格式,单个 html 文件达到 10-200M。采用 python 脚本,批量将 html 中的 table 批量转为 Excel,并导出到文件。
主要流程
- 采用
Beautifulsoup 4 库进行解析,获取 html 中的 table;
- 采用
pandas 解析 table 库中的数据,并进行整合;
- 将整合后的
DataFrame 导出到各 Sheet,并保存到文件。

依赖包
主要代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
| from bs4 import BeautifulSoup import pandas as pd print('Reading Started') html_id=2 html=BeautifulSoup(open('Ma-%s-statistics.html'%html_id,'r').read()) tables=html.find_all('table',class_='Data') print('Reading Finished') SHEETS=[] for i in range(8): SHEETS.append(pd.DataFrame()) for i,table in enumerate(tables): df = pd.read_html(str(table))[0] if i/8<1: SHEETS[i%8]=df else: SHEETS[i%8]=SHEETS[i%8].append(df) print('Handling %s/%s'%(i,len(tables)))
writer = pd.ExcelWriter('output-%s.xlsx'%html_id) for i in range(8): SHEETS[i%8].to_excel(writer,'Sheet%s'%i,index=False) print('Saving %s/%s'%(i,8)) writer.save() print('Finished')
|
Author
Dorad, ddxid@outlook.com