10

我收到一个 Unicode 错误:UnicodeEncodeError: 'charmap' codec can't encode character u'\xa9' in position 822: character maps to <undefined>

这似乎是一个标准的版权符号,在 HTML 中是 ©。我一直无法找到解决办法。我什至尝试了一个自定义函数来用空格替换副本,但同样的错误也失败了。

import sys
import pprint
import mechanize
import cookielib
from bs4 import BeautifulSoup
import html2text
import lxml

def MakePretty():

def ChangeCopy(S):
    return S.replace(chr(169)," ")
br = mechanize.Browser()

# Cookie Jar
cj = cookielib.LWPCookieJar()
br.set_cookiejar(cj)

# Browser options
br.set_handle_equiv(True)
#br.set_handle_gzip(True)
br.set_handle_redirect(True)
br.set_handle_referer(True)
br.set_handle_robots(False)

# Follows refresh 0 but not hangs on refresh > 0
br.set_handle_refresh(mechanize._http.HTTPRefreshProcessor(), max_time=1)

# User-Agent (this is cheating, ok?)
br.addheaders = [('User-agent', 'Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.0.1) Gecko/2008071615 Fedora/3.0.1-1.fc9 Firefox/3.0.1')]

# The site we will navigate into, handling its session
# Open the site
br.open('http://www.thesitewizard.com/faqs/copyright-symbol.shtml')
html = br.response().read()
soup = BeautifulSoup(html)
print soup.prettify()

if __name__ == '__main__':
    MakePretty()

如何通过版权符号美化?我在网上搜索了一个无济于事的解决方案(或者我可能不明白,因为我对 Python 和抓取还很陌生)。

谢谢你的帮助。

4

4 回答 4

27

我有同样的问题。这可能对您有用:

print soup.prettify().encode('UTF-8')

于 2012-11-23T07:32:39.243 回答
1

The page http://www.thesitewizard.com/faqs/copyright-symbol.shtml is sent without specifying character encoding. The page itself specifies the encoding as ISO-8859-1 in a meta tag, but only after the occurrence of the “©” character. So clients have to make a guess, and the guess may be wrong. If the client guesses UTF-8, then it will see the bit A9, which is a data error in UTF-8 data.

So it seems that you need to set the encoding (to ISO-8859-1, or more safely to windows-1252) when reading the data. This is of course an ad hoc solution only; it makes no sense to fix the encoding in general.

于 2012-07-12T17:53:31.600 回答
0

您正在使用chr(),这里是错误的,因为它需要 ASCII 并且只能达到 127/0x7F(尽管流行的民间传说,ASCII 只是 7 位)。0xA9 / © 是 Unicode,所以你应该使用它unichr(169)

于 2012-07-12T17:57:40.007 回答
0

只是在格式化程序功能中更改为 unichr 不起作用。最终使用了 decode(formatter=blah) ,它确实返回了没有版权符号的未格式化的 html。保存该 html 并将其输入 prettify 以达到目的。

于 2012-07-13T13:58:26.417 回答