Joh*_*000 5 html python text html-content-extraction
我正在尝试从任意html页面中提取文本.有些页面(我无法控制)有错误的html或脚本,这使得这很困难.此外,我在一个共享的托管环境,所以我可以安装任何python库,但我不能只在服务器上安装我想要的东西.
pyparsing和html2text.py似乎也不适用于格式错误的html页面.
示例URL是http://apnews.myway.com/article/20091015/D9BB7CGG1.html
我目前的实施大致如下:
# Try using BeautifulSoup 3.0.7a
soup = BeautifulSoup.BeautifulSoup(s)
comments = soup.findAll(text=lambda text:isinstance(text,Comment))
[comment.extract() for comment in comments]
c=soup.findAll('script')
for i in c:
i.extract()
body = bsoup.body(text=True)
text = ''.join(body)
# if BeautifulSoup can't handle it,
# alter html by trying to find 1st instance of "<body" and replace everything prior to that, with "<html><head></head>"
# try beautifulsoup again with new html
Run Code Online (Sandbox Code Playgroud)
如果beautifulsoup仍然不起作用,那么我采用一种启发式方法来查看第一个字符,最后一个字符(看看它们是否看起来像是一个代码行#<;然后取一行代码然后检查是否有令牌是英文单词或数字.如果很少的标记是单词或数字,那么我猜这行是代码.
我可以使用机器学习来检查每一行,但这看起来有点贵,我可能需要训练它(因为我不太了解无监督的学习机器),当然也可以写它.
任何建议,工具和策略都是最受欢迎的.此外,我意识到后一部分相当混乱,因为如果我得到一行确定包含代码,我现在扔掉整行,即使行中有少量实际的英文文本.
尽量不要笑,但是:
class TextFormatter:
def __init__(self,lynx='/usr/bin/lynx'):
self.lynx = lynx
def html2text(self, unicode_html_source):
"Expects unicode; returns unicode"
return Popen([self.lynx,
'-assume-charset=UTF-8',
'-display-charset=UTF-8',
'-dump',
'-stdin'],
stdin=PIPE,
stdout=PIPE).communicate(input=unicode_html_source.encode('utf-8'))[0].decode('utf-8')
Run Code Online (Sandbox Code Playgroud)
我希望你有lynx!
| 归档时间: |
|
| 查看次数: |
1917 次 |
| 最近记录: |