将html解析为其页面显示内容文本.txt的所有方法
时间: 2023-12-03 07:02:40 浏览: 92
下面介绍几种将HTML解析为页面显示内容文本的方法:
1. 使用Python的BeautifulSoup库
- 首先安装BeautifulSoup库:pip install beautifulsoup4
- 然后使用以下Python代码将HTML解析为文本:
```
from bs4 import BeautifulSoup
with open("example.html") as fp:
soup = BeautifulSoup(fp, "html.parser")
text = soup.get_text()
with open("example.txt", "w") as fp:
fp.write(text)
```
其中,"example.html"是要解析的HTML文件路径,"example.txt"是输出文本文件路径。
2. 使用Python的lxml库
- 首先安装lxml库:pip install lxml
- 然后使用以下Python代码将HTML解析为文本:
```
from lxml import etree
with open("example.html") as fp:
html = fp.read()
root = etree.HTML(html)
text = root.xpath("//text()")
with open("example.txt", "w") as fp:
fp.write("".join(text))
```
其中,"example.html"是要解析的HTML文件路径,"example.txt"是输出文本文件路径。
3. 使用在线工具
还有一些在线工具可以将HTML解析为文本,例如Online HTML to Text Converter和HTML to Text Online Converter等。只需将HTML粘贴到输入框中,然后点击转换按钮即可得到输出的文本。
阅读全文
相关推荐


















