当前位置:   article > 正文

Python:获取html表格数据、html表格保存Excel_python html格式的字符串表格转excel

python html格式的字符串表格转excel
  1. # !/usr/bin/env python
  2. # -*-coding:utf-8 -*-
  3. import os.path
  4. import bs4,shutil,time
  5. from pandas.core.frame import DataFrame
  6. def get_html_tabledata(htmlpath,tableindex: int = 0):
  7. """
  8. html文件,获取表格数据
  9. :param htmlpath: html文件路径
  10. :param tableindex: table索引,int,默认为0
  11. :return:字典列表
  12. """
  13. with open(htmlpath, 'r+',encoding='UTF-8') as f:
  14. s = f.read()
  15. wb = s.strip().replace('\ufeff', '')
  16. soup = bs4.BeautifulSoup(wb, 'lxml') # 解析html
  17. # 获取指定表格的数据
  18. table=soup.findAll("table")[tableindex] # 读取第二个表格
  19. table_rows = table.findAll("tr") # 获得表格中行的集合
  20. # 获取表格第一行作为字典keykey
  21. keys = [table_rows[0].findAll(['th', 'td'])[i].getText().strip() for i in range(len(table_rows[0].findAll(['th', 'td']))) ]
  22. tabledata = []
  23. for table_row in table_rows[1:]:
  24. row = table_row.findAll(['th', 'td']) # 获取th/td标签
  25. linedata = {keys[i]: row[i].getText().strip() for i in range(len(row))} # 每行数据按字段返回:键值对
  26. tabledata.append(linedata)
  27. # print(tabledata)
  28. return tabledata
  29. def html_to_excel(htmlpath,excelpath,tableindex: int = 0):
  30. """html文件,将指定表格数据保存到excel文件"""
  31. tabledata = get_html_tabledata(htmlpath,tableindex)
  32. data = DataFrame(tabledata) # 将字典列表转为表格样式
  33. # print(data,len(data),len(data.columns)) # 获取行数:len(df);获取列数:len(df.columns)
  34. # 写入excel
  35. data.to_excel(excelpath, index=False, header=True) # 输出为表,不带列号,输出文件名
  36. if __name__ == '__main__':
  37. htmlpath = r'C:\Users\yhen\Downloads\2022-06-17T13_51_06+0800.html'
  38. tabledata = get_html_tabledata(htmlpath,1)
  39. tabledata = sorted(tabledata,key=lambda x:x['关键字'])
  40. print(tabledata)

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/不正经/article/detail/249900
推荐阅读
相关标签
  

闽ICP备14008679号