# pip install readability-lxml
# pip install html2text
import requests
from readability import Document
import html2text
response = requests.get('http://www.infzm.com/content/146720')
doc = Document(response.text)
print(doc.title())
content = html2text.html2text(doc.summary())
print(content)
"""
readability可以在不使用xpath,re等时,自动识别返回的response中的标题,正文等。但是正文时常会有html标签
html2text可以处理掉文字中的html标签,
"""
"""
可以这样使用忽略标签属性的干扰
h=html2text.HTML2Text()
h.ignore_links=True
print h.handle("<p>Hello, <a href='http://earth.google.com/'>world</a>!") # 输出Hello world
"""
另外还有newspaper 也与readability相似。

本文介绍了一种利用Python自动从网页中提取标题和正文内容的方法。通过使用readability库,可以有效地解析网页并去除无关元素,再结合html2text库进一步清理HTML标签,最终得到纯净的文字内容。此外还提到了newspaper库作为类似的功能实现方案。
756

被折叠的 条评论
为什么被折叠?



