gpt4 book ai didi

python - 获取 url 时出现 UnicodeEncodeError

转载 作者:太空狗 更新时间:2023-10-29 20:23:10 24 4
gpt4 key购买 nike

我在尝试使用 lxml 获取 HTML 文档中的所有文本节点时遇到此问题,但我收到 UnicodeEncodeError: 'ascii' codec can't encode character u'\xe9' in position 8995: ordinal not in范围(128)。但是,当我尝试找出此页面的编码类型时 (encoding = chardet.detect(response)['encoding']),它说它是 utf-8。单个页面有 utf-8 和 ascii 似乎很奇怪。实际上,这是:

fromstring(response).text_content().encode('ascii', 'replace')

解决问题。

这是我的代码:

from lxml.html import fromstring
import urllib2
import chardet
request = urllib2.Request(my_url)
request.add_header('User-Agent',
'Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.0)')
request.add_header("Accept-Language", "en-us")
response = urllib2.urlopen(request).read()

print encoding
print fromstring(response).text_content()

输出:

utf-8
UnicodeEncodeError: 'ascii' codec can't encode character u'\xe9' in position 8995: ordinal not in range(128)

我该怎么做才能解决这个问题?。请记住,我想对其他几个页面执行此操作,因此我不想单独编码。

更新:

也许这里还有其他事情发生。当我在终端上运行这个脚本时,我得到了正确的输出,但是当我在 SublimeText 中运行它时,我得到了 UnicodeEncodeError... ¿?

更新 2:

当我使用此输出创建文件时也会发生这种情况。 .encode('ascii', 'replace') 正在运行,但我想要一个更通用的解决方案。

问候

最佳答案

你能试试用 repr() 包装你的字符串吗? This article可能有帮助。

print repr(fromstring(response).text_content())

关于python - 获取 url 时出现 UnicodeEncodeError,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11059714/

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