【问题标题】:'charmap' codec can't encode character '\xae' While Scraping a Webpage'charmap' 编解码器在抓取网页时无法编码字符 '\xae'
【发布时间】:2014-11-07 17:31:37
【问题描述】:

我正在使用Python 使用BeautifulSoap 进行网络抓取 我收到此错误

'charmap' codec can't encode character '\xae' in position 69: character maps to <undefined>

抓取网页时

这是我的Python

hotel = BeautifulSoup(state.)
print (hotel.select("div.details.cf span.hotel-name a"))
# Tried:  print (hotel.select("div.details.cf span.hotel-name a")).encode('utf-8')

【问题讨论】:

标签: python web-scraping beautifulsoup


【解决方案1】:

当我们尝试.encode() 一个已经编码的字节字符串时,我们通常会在这里遇到这个问题。所以你可以尝试先解码它,如

html = urllib.urlopen(link).read()
unicode_str = html.decode(<source encoding>)
encoded_str = unicode_str.encode("utf8")

举个例子:

html = '\xae'
encoded_str = html.encode("utf8")

失败

UnicodeDecodeError: 'ascii' codec can't decode byte 0xa0 in position 0: ordinal not in range(128)

同时:

html = '\xae'
decoded_str = html.decode("windows-1252")
encoded_str = decoded_str.encode("utf8")
print encoded_str
®

成功无误。请注意,“windows-1252”是我用作示例的东西。我从 chardet 得到这个,它有 0.5 的信心认为它是正确的! (好吧,正如给出的 1 个字符长度的字符串,您期望什么)您应该将其更改为从 .urlopen().read() 返回的字节字符串的编码,以适用于您检索到的内容。

【讨论】:

  • 你注意到你必须使用 decode('latin-1') 而不是 encode('latin-1')。
  • 我改变了我的答案。希望对您有所帮助。
猜你喜欢
  • 2015-11-21
  • 1970-01-01
  • 2015-01-21
相关资源
最近更新 更多