我在python 2.7.1上使用Beautiful Soup 3.2。
我最近一直试图让一些简单的工作,但它 看起来相当棘手:
我执行以下操作:
temp=BeautifulSoup(urllib2.urlopen(urlList[1], None,15))
然而,我收到错误:
File "/home/foo/k/kat/BeautifulSoup.py", line 1519, in __init__
BeautifulStoneSoup.__init__(self, *args, **kwargs)
File "/home/foo/k/kat/BeautifulSoup.py", line 1144, in __init__
self._feed(isHTML=isHTML)
File "/home/foo/k/kat/BeautifulSoup.py", line 1186, in _feed
SGMLParser.feed(self, markup)
File "/usr/lib/python2.7/sgmllib.py", line 104, in feed
self.goahead(0)
File "/usr/lib/python2.7/sgmllib.py", line 143, in goahead
k = self.parse_endtag(i)
File "/usr/lib/python2.7/sgmllib.py", line 320, in parse_endtag
self.finish_endtag(tag)
File "/usr/lib/python2.7/sgmllib.py", line 358, in finish_endtag
method = getattr(self, 'end_' + tag)
UnicodeEncodeError: 'ascii' codec can't encode character u'\xfa' in
position 4: ordinal not in range(128)
如果我再次运行相同的循环,有时候,我也会得到:
File "/home/foo/k/kat/BeautifulSoup.py", line 1519, in __init__
BeautifulStoneSoup.__init__(self, *args, **kwargs)
File "/home/foo/k/kat/BeautifulSoup.py", line 1144, in
__init__
self._feed(isHTML=isHTML)
File "/home/foo/k/kat/BeautifulSoup.py", line 1186, in _feed
SGMLParser.feed(self, markup)
File "/usr/lib/python2.7/sgmllib.py", line 104, in feed
self.goahead(0)
File "/usr/lib/python2.7/sgmllib.py", line 143, in goahead
k = self.parse_endtag(i)
File "/usr/lib/python2.7/sgmllib.py", line 320, in parse_endtag
self.finish_endtag(tag)
File "/usr/lib/python2.7/sgmllib.py", line 358, in finish_endtag
method = getattr(self, 'end_' + tag)
UnicodeEncodeError: 'ascii' codec can't encode characters in position
4-5: ordinal not in range(128)
如何避免此错误?显然sgmllib.py出了点问题。
我尝试了SOF的一些解决方案:
*]尝试soup = BeautifulSoup(page, fromEncoding=<encoding of the page>)
结果:Dosent工作,同样的错误。
*]尝试将我的sgmllib.py从2.7.2版本升级到我的2.7.1版本 结果:Dosent工作,同样的错误。
*]尝试html = BeautifulSoup(page.encode('utf-8'))
结果:Dosent工作,同样的错误。
我很感激有关如何解决此编码错误的任何建议。
答案 0 :(得分:4)
在您的模块中尝试此代码
if __name__ == "__main__":
reload(sys)
sys.setdefaultencoding("utf-8")