相关疑难解决方法(0)

UnicodeEncodeError:'ascii'编解码器无法对位置20中的字符u'\ xa0'进行编码:序数不在范围内(128)

我在处理从不同网页(在不同网站上)获取的文本中的unicode字符时遇到问题.我正在使用BeautifulSoup.

问题是错误并不总是可重现的; 它有时适用于某些页面,有时候,它会通过抛出一个UnicodeEncodeError.我已经尝试了几乎所有我能想到的东西,但是我没有找到任何可以持续工作的东西而不会抛出某种与Unicode相关的错误.

导致问题的代码部分之一如下所示:

agent_telno = agent.find('div', 'agent_contact_number')
agent_telno = '' if agent_telno is None else agent_telno.contents[0]
p.agent_info = str(agent_contact + ' ' + agent_telno).strip()
Run Code Online (Sandbox Code Playgroud)

以下是运行上述代码段时在SOME字符串上生成的堆栈跟踪:

Traceback (most recent call last):
  File "foobar.py", line 792, in <module>
    p.agent_info = str(agent_contact + ' ' + agent_telno).strip()
UnicodeEncodeError: 'ascii' codec can't encode character u'\xa0' in position 20: ordinal not in range(128)
Run Code Online (Sandbox Code Playgroud)

我怀疑这是因为某些页面(或更具体地说,来自某些站点的页面)可能被编码,而其他页面可能是未编码的.所有这些网站都位于英国,并提供供英国消费的数据 - 因此,没有与内部化或处理用英语以外的任何文字处理的文本相关的问题.

有没有人有任何想法如何解决这个问题,以便我可以一致地解决这个问题?

python unicode beautifulsoup python-2.x python-unicode

1222
推荐指数
24
解决办法
156万
查看次数

为什么我们不应该在py脚本中使用sys.setdefaultencoding("utf-8")?

我见过很少的py脚本在脚本的顶部使用它.在什么情况下应该使用它?

import sys
reload(sys)
sys.setdefaultencoding("utf-8")
Run Code Online (Sandbox Code Playgroud)

python encoding utf-8 python-2.x sys

158
推荐指数
3
解决办法
18万
查看次数

sys.setdefaultencoding('utf-8')的危险

sys.setdefaultencoding('utf-8')在Python 2中存在令人沮丧的设置趋势.任何人都可以列出问题的真实例子吗?论证喜欢it is harmfulit hides bugs听起来不太令人信服.

更新:请注意,这个问题只是关于utf-8,它不是关于改变默认编码"一般情况下".

如果可以,请举一些代码示例.

python encoding utf-8 python-2.x

33
推荐指数
3
解决办法
2万
查看次数