HTML代码提取文本信息
用python对HTML代码进行文本信息的提取,思路非常简单,就是获取HTML中的所有标签,并去除标签只留下文字。使用Beautifulsoup进行处理,去除标签以及js代码与style代码。
__author__ = 'Teer'
from bs4 import BeautifulSoup
fin = open('D:/1.html', 'r')
html = fin.read()
fin.close()
soup = BeautifulSoup(html)
for i in soup('style') + soup('script'):
i.extract()
out_file = open('D:/soup.txt', 'wb')
out_file.write(soup.get_text(strip=True).encode('utf-8'))
out_file.close()
其实原本是想对HTML进行正文提取,但是尝试过各种正文提取库之后,包括boilerpipe、goose、dragnet、newspaper等之后,发现不能保证正文的提取准确率,因此只好选择了提取全部文本这种比较保险的方式,如果有更好的方法的话,也希望有人能告诉我~