我正在使用 urlfetch 来获取 URL。当我尝试将其发送到 html2text 函数(删除所有 HTML 标签)时,我收到以下消息:
UnicodeEncodeError: 'charmap' codec can't encode characters in position ... character maps to <undefined>
我一直在尝试处理字符串上的编码('UTF-8','忽略'),但我不断收到此错误。
有任何想法吗?
Thanks,
Joel
一些代码:
result = urlfetch.fetch(url="http://www.google.com")
html2text(result.content.encode('utf-8', 'ignore'))
以及错误消息:
File "C:\Python26\lib\encodings\cp1252.py", line 12, in encode
return codecs.charmap_encode(input,errors,encoding_table)
UnicodeEncodeError: 'charmap' codec can't encode characters in position 159-165: character maps to <undefined>
你需要decode您首先获取的数据!使用哪个编解码器?取决于您获取的网站。
当你有 unicode 并尝试使用它进行编码时some_unicode.encode('utf-8', 'ignore')
我无法想象它如何引发错误。
好的,你需要做什么:
result = fetch('http://google.com')
content_type = result.headers['Content-Type'] # figure out what you just fetched
ctype, charset = content_type.split(';')
encoding = charset[len(' charset='):] # get the encoding
print encoding # ie ISO-8859-1
utext = result.content.decode(encoding) # now you have unicode
text = utext.encode('utf8', 'ignore') # encode to uft8
这并不是很强大,但它应该为您指明方向。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)