gpt4 book ai didi

python - Beautiful soup 中的 UnicodeEncodeError (python 2.7.1)

转载 作者:行者123 更新时间:2023-11-28 23:03:04 24 4
gpt4 key购买 nike

我在这里使用 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>)结果:执行工作,同样的错误。

*] 尝试将我的 sgmllib.py 从 2.7.2 版本升级到我的 2.7.1 版本结果:执行工作,同样的错误。

*] 已尝试 html = BeautifulSoup(page.encode('utf-8'))结果:执行工作,同样的错误。

如果有任何关于如何解决此编码错误的建议,我将不胜感激。

最佳答案

在你的模块中尝试这段代码

if __name__ == "__main__":
reload(sys)
sys.setdefaultencoding("utf-8")

关于python - Beautiful soup 中的 UnicodeEncodeError (python 2.7.1),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8986849/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com