【问题标题】:'ascii' codec error in beautifulsoupBeautifulsoup 中的“ascii”编解码器错误
【发布时间】:2010-11-16 17:56:24
【问题描述】:

我正在使用 beautifulsoup 从 html 页面中抓取数据。直到昨天一切都很好。但现在我得到了错误:

'ascii' codec can't encode character u'\xa9' in position 86700: ordinal not in range(128)

我正在使用代码:

import urllib2
from BeautifulSoup import BeautifulSoup

page = urllib2.urlopen(url).read()
soup = BeautifulSoup(page)

这给了我错误。

【问题讨论】:

    标签: python beautifulsoup


    【解决方案1】:

    一个疯狂的猜测:

    尝试指定页面的编码?

    soup = BeautifulSoup(page, fromEncoding=<encoding of the page>)
    

    这也可能是 Python 安装的问题。如果你在没有 BeautifulSoup 的情况下打印非 ASCII 字符,你会面临同样的问题吗?如果是,则需要设置编码:

    import sys
    sys.setdefaultencoding("utf-8") # or whatever you want the default encoding to be.
    

    【讨论】:

    • 你需要reload(sys),因为sys.setdefaultencoding()在site.py中被删除了。
    • 仍然不工作,soup = BeautifulSoup(page, fromEncoding="utf-8") 给我同样的错误。正如我的解释器所说,sys 没有属性 setdefaultencoding。
    • 没有python安装问题。我查过了。
    • 'sys.getdefaultencoding()' 返回什么?
    • 好吧。我想通了。这是 BeautifulSoap 问题。 BeautifulSoap 文档本身表明它有一些错误。所以,我降级到 3.0.7 并且工作正常。感谢您的建议。 +1
    【解决方案2】:

    黑暗中的野刺:您正在阅读的页面没有明确声明编码但不是 7 位 ASCII?

    【讨论】:

      猜你喜欢
      • 2018-02-02
      • 2015-01-28
      • 2017-03-31
      • 1970-01-01
      • 1970-01-01
      • 2015-02-03
      • 2019-09-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多