python - 无法将 HTML 从网站正确转换为文本

标签 python python-2.7 text web-scraping beautifulsoup

编辑:我不敢相信 BeautifullSoup 实际上无法正确解析 HTML。实际上我可能做错了什么,但如果我不这样做,这就是一个非常业余的模块。

我正在尝试从网络获取文本,但我无法这样做,因为我总是在大多数句子中收到一些奇怪的字符。我从来没有得到过包含“isn't”这样的单词的句子正确。

useragent = {'User-Agent':'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_7_4) AppleWebKit/536.11 (KHTML, like Gecko) Chrome/20.0.1132.57 Safari/536.11'}
request = urllib2.Request('SomeURL',None,useragent)
myreq = urllib2.urlopen(request, timeout = 5)
html = myreq.read()

#get paragraphs
soup = BeautifulSoup(html)
textList = soup.find_all('p')
mytext = ""
for par in textList:
    if len(str(par))<2000: 
    print par
    mytext +=" " +  str(par)

 print "the text is ", mytext

结果包含一些奇怪的字符:

The plural of “comedo� is comedomes�.</p>
Surprisingly, the visible black head isn’t caused by dirt

显然我想得到 is not 而不是 isn't。我该怎么办?

最佳答案

我认为问题出在您的系统输出编码上,它无法正确输出编码字符,因为它超出了显示的字符范围。

BeautifulSoup4 旨在完全支持 HTML 实体。

注意这些命令的奇怪行为:

>python temp.py
...
ed a blackhead. The plural of ÔÇ£comedoÔÇØ is comedomesÔÇØ.</p>
...

>python temp.py > temp.txt

>cat temp.txt
....
ed a blackhead. The plural of "comedo" is comedomes".</p> <p> </p> <p>Blackheads is an open and wide
....

我建议将输出写入文本文件,或者使用不同的终端/更改终端设置以支持更广泛的字符。

关于python - 无法将 HTML 从网站正确转换为文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22091938/

相关文章:

performance - 快速计算二进制numpy数组的质心

python - Pandas MemoryError while pd.concat

javascript - 从上面的链接获取文本 - Jquery

python - 在 SQLAlchemy 应用程序的单元测试中使用 Alembic?

Python - 如何从扩展命名空间导入父包

python - python中列表的深拷贝

python - 数据集中的成对比较

python - 在python中解析一行的文本文件

java - 如何创建格式化文本以在 Java Swing 组件(JTextPane、JEditorPane...)中显示

python - 断言整数在范围内