html2text.py 1.1 KB

123456789101112131415161718192021222324252627282930313233343536
  1. #coding:utf8
  2. from bs4 import BeautifulSoup
  3. import re
  4. def html2text_with_tablehtml(_html):
  5. # 如果输入是字符串,使用 BeautifulSoup 解析
  6. if isinstance(_html, str):
  7. _soup = BeautifulSoup(_html, "lxml")
  8. else:
  9. _soup = _html
  10. # 用于存储处理后的文本
  11. result_parts = []
  12. _find = False
  13. # 遍历所有直接子元素
  14. for child in _soup.find_all(recursive=False):
  15. if child.name in ["table", "tbody"]:
  16. # 如果是表格或表格主体,保留 HTML 代码
  17. result_parts.append(str(child))
  18. else:
  19. # 递归处理其他元素并转换为文本
  20. text = html2text_with_tablehtml(child)
  21. result_parts.append(text)
  22. _find = True
  23. if not _find:
  24. result_parts.append(str(_soup.get_text()))
  25. # 将所有处理后的部分连接成一个字符串
  26. result = "\n".join(result_parts)
  27. return result
  28. if __name__ == '__main__':
  29. _html = "<div><p>这是一个p</p><table><tr><td>这是一个td</td></tr></table></div>"
  30. print(html2text_with_tablehtml(_html))