【发布时间】:2013-05-28 06:49:31
【问题描述】:
我正在下载一个带有 urllib2 的页面并将其加载到 BeautifulSoup 中:
from bs4 import BeautifulSoup as Soup
import urllib2
baseHTML = 'http://forums.macrumors.com/'
baseForum = 'forumdisplay.php?f=109'
forumHTML = urllib2.urlopen(baseHTML+baseForum).read()
page = Soup(forumHTML)
print forumHTML
print page
打印forumHTML时,一切正常,得到返回的html完全没问题。
但是,当打印page 时,此时 HTML 会出现乱码:
<a href="showthread.php?t=324487" id="thread_title_324487">iPhone Tips and Tricks thread</a>
<span class="smallf">o n t " s t y l e = " w h i t e - s p a c e
如您所见,BeautifulSoup 在错误的地方添加了>,原因不明。
这是forumHTML中的相同HTML:
<a href="showthread.php?t=324487" id="thread_title_324487">iPhone Tips and Tricks thread</a>
<span class="smallfont" style="white-space
为什么会发生这种情况?我在 Windows 64 位上使用 python 2.7,如果这很重要的话。
【问题讨论】:
-
我敢打赌,这是因为 bs4 默认会尝试转义 '&'、'' 等字符(请参阅 docs)。如果你运行
print(soup.prettify(formatter=None)),你会看到相同的html吗? -
安装
html5lib,它应该可以工作。 -
安装
html5lib和使用prettify都不起作用 - HTML 仍然是错误的。
标签: python html beautifulsoup urllib2