【问题标题】:Python + BeautifulSoup: Encoding ErrorPython + BeautifulSoup:编码错误
【发布时间】:2016-12-28 06:59:37
【问题描述】:

如果我运行这段代码:

for link in soup.findAll('a'):
    href = link.get('href')
    href = str(href)

最后一行出现以下错误

href = str(href)
UnicodeEncodeError: 'ascii' codec can't encode character u'\u2018' in position 68: ordinal not in range(128)

当我尝试对变量进行编码时,如下图:

for link in soup.findAll('a'):
    href = link.get('href')
    href = href.encode('utf-8')
    href = str(href)

我收到以下错误:

href = href.encode('utf-8')
AttributeError: 'NoneType' object has no attribute 'encode'

我在这里和其他地方查看了多个帖子,但没有一个提供合适的解决方案。我对python相当陌生。请帮忙。

【问题讨论】:

  • 您可以使用 try/catch 打印导致错误的值

标签: python python-2.7 encoding beautifulsoup


【解决方案1】:

在我的母语中,我们有很多“áçéàó”字符,所以我经常发现自己处于类似的情况,而且大多数解码/编码技巧都没有奏效。

在我的代码开头找到了重置 sys 默认语言的方法:

import sys

reload(sys)
sys.setdefaultencoding('latin-1')

希望这也能帮助您解决问题。

【讨论】:

  • 谢谢...我已经尝试过这个和 UTF-8 作为默认编码。他们都没有工作。
【解决方案2】:

如果有人遇到过这个问题,我是这样解决的:

理想情况下,对于编码问题,这应该有效:

href = href.encode('utf-8')
href = str(href)

但是在我正在清理的一组网页中,有几个页面没有在href 变量中存储任何值,导致一些 NoneType 返回。这使str(href) 声明失败。所以我终于做到了:

for link in soup.findAll('a'):
    href = link.get('href')
    if href is None:
        href = ""
    href = str(href.encode('utf-8'))

如果hrefNoneType,最好将其分配给空字符串,以防止代码中出现任何类型特定问题。

我对 u\2018 和 u\2019 字符的观察之一是,它们通常不会出现在链接本身中,而是出现在链接的附加属性中。一般是?attribute=后面的文字。因此,如果属性在您的清理中并不重要,使用如下语句可以解决您的所有问题。

href = href.split("?")[0]

【讨论】:

    猜你喜欢
    • 2011-08-19
    • 2015-01-29
    • 2015-10-07
    • 2015-11-17
    • 2019-07-08
    • 2012-05-18
    • 1970-01-01
    • 2015-04-28
    相关资源
    最近更新 更多