问题在于错误并不总是可重现的;它有时可以与某些页面一起工作,有时会通过抛出
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()
当运行上面的代码片段时,以下是某些字符串产生的堆栈跟踪:
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)
我怀疑这是因为有些页面(或更具体地说,来自某些网站的页面)可能被编码,而其他页面可能没有编码。所有网站都位于英国,提供的数据面向英国市场 - 因此不存在与国际化或处理非英语文本相关的问题。
有没有人有任何想法如何解决这个问题,以便我可以一致地修复它?
import os; import locale; os.environ["PYTHONIOENCODING"] = "utf-8"; myLocale=locale.setlocale(category=locale.LC_ALL, locale="en_GB.UTF-8"); ... print(myText.encode('utf-8', errors='ignore'))
。 - hhh$ export PYTHONIOENCODING=utf8
。 - Noam Manos.encode('utf-8').strip()
。它的作用是从字符串中删除最后一个\n
,这之前会出现问题,即使之前使用了encode('utf-8')。 - Indrajeet Gour