use*_*411 10 python unicode prettify beautifulsoup
我收到一个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()
Run Code Online (Sandbox Code Playgroud)
如何通过版权符号获得美化?我已经在网上搜索了一个无济于事的解决方案(或者我可能不理解,因为我对Python和刮擦是相当新的).
谢谢你的帮助.
kmo*_*ote 27
我有同样的问题.这可能对你有用:
print soup.prettify().encode('UTF-8')
发送页面http://www.thesitewizard.com/faqs/copyright-symbol.shtml时未指定字符编码。页面本身在标签中将编码指定为 ISO-8859-1 meta,但仅在 \xe2\x80\x9c\xc2\xa9\xe2\x80\x9d 字符出现之后才指定。所以客户必须做出猜测,而猜测可能是错误的。如果客户端猜测UTF-8,那么它将看到位A9,这是UTF-8数据中的数据错误。
所以看来您在读取数据时需要设置编码(为ISO-8859-1,或更安全地为windows-1252)。这当然只是一个临时解决方案;一般来说,修复编码是没有意义的。
\n| 归档时间: |
|
| 查看次数: |
7916 次 |
| 最近记录: |