【问题标题】:stuck with encodings in python with BeautifulSoup使用 BeautifulSoup 卡在 python 中的编码
【发布时间】:2012-01-31 01:50:05
【问题描述】:

该页面以 UTF-8 编码,并且使用 python 的 HTMLParser 它运行良好,没有UnicodeDecodeError,但是当我尝试使用 BeautifulSoup 解析它时确实出现错误。 我已经尝试过_*_ 编码:utf-8 _*_.encode('utf-8') 到处都是,但我仍然收到错误

import urllib
from BeautifulSoup import BeautifulSoup
args=urllib.urlencode({'keywords':'magic'})
doc=urllib.urlopen('http://www.example.com/submit', args)
soup=BeautifulSoup(doc)
stuff = soup.findAll('section',id='banner')
print stuff

Traceback (most recent call last):
      File "test.py", line 7, in <module>
        print stuff
    UnicodeEncodeError: 'ascii' codec can't encode character u'\xed' in position 112: ordinal not in range(128)

【问题讨论】:

    标签: python unicode encoding beautifulsoup


    【解决方案1】:

    好的,我在上次尝试中找到了解决方案,也许它会帮助其他有同样问题的人。 它需要编码,而不是解码

    print( [e.encode('utf-8', 'ignore') for e in stuff] )
    

    【讨论】:

      【解决方案2】:

      打印时不应出现UnicodeEncodeError: 'ascii'.. 错误。如果您的locale 已损坏或设置为C,通常会导致这种情况。然后 Python 无法在标准输出流上设置适当的编码器。

      运行locale 并检查错误或警告。

      如果您无法修复您的语言环境,您通常可以通过将环境中的 PYTHONIOENCODING 设置为与您的终端仿真匹配的编码来覆盖 Python 的标准输出编码器。通常你可以通过:

      export PYTHONIOENCODING=UTF-8
      

      PYTHONIOENCODING=UTF-8 python my_script.py
      

      【讨论】:

        猜你喜欢
        • 2011-07-02
        • 1970-01-01
        • 2016-12-28
        • 2015-10-07
        • 2015-04-28
        • 2015-11-17
        • 2011-08-19
        • 2015-01-29
        • 2021-07-29
        相关资源
        最近更新 更多