【问题标题】:BeautifulSoup findall with class attribute- unicode encode errorBeautifulSoup findall 与类属性 - unicode 编码错误
【发布时间】:2011-04-21 16:18:02
【问题描述】:

我正在使用 BeautifulSoup 从Hacker News 中提取新闻故事(只是标题),并且到目前为止 -

import urllib2
from BeautifulSoup import BeautifulSoup

HN_url = "http://news.ycombinator.com"

def get_page():
    page_html = urllib2.urlopen(HN_url) 
    return page_html

def get_stories(content):
    soup = BeautifulSoup(content)
    titles_html =[]

    for td in soup.findAll("td", { "class":"title" }):
        titles_html += td.findAll("a")

    return titles_html

print get_stories(get_page()

)

然而,当我运行代码时,它给出了一个错误-

Traceback (most recent call last):
  File "terminalHN.py", line 19, in <module>
    print get_stories(get_page())
UnicodeEncodeError: 'ascii' codec can't encode character u'\xe2' in position 131: ordinal not in range(128)

如何让它工作?

【问题讨论】:

    标签: python beautifulsoup


    【解决方案1】:

    因为 BeautifulSoup 在内部使用 unicode 字符串。将 unicode 字符串打印到控制台将导致 Python 尝试将 unicode 转换为 Python 的默认编码,通常是 ascii。对于非 ascii 网站,这通常会失败。您可以通过谷歌搜索“python + unicode”来了解有关 Python 和 Unicode 的基础知识。同时转换 你的 unicode 字符串使用 utf-8

    print some_unicode_string.decode('utf-8')
    

    【讨论】:

    • 您希望.encode('utf-8') 从 Unicode 字符串转换为 UTF-8 编码字符串。
    【解决方案2】:

    关于您的代码需要注意的一点是,findAll 返回一个列表(在本例中为 BeautifulSoup 对象的列表),而您只需要标题。您可能想改用find。而不是打印出 BeautifulSoup 对象的列表,而是说您只想要标题。以下工作正常,例如:

    import urllib2
    from BeautifulSoup import BeautifulSoup
    
    HN_url = "http://news.ycombinator.com"
    
    def get_page():
        page_html = urllib2.urlopen(HN_url) 
        return page_html
    
    def get_stories(content):
        soup = BeautifulSoup(content)
        titles = []
    
        for td in soup.findAll("td", { "class":"title" }):
            a_element = td.find("a")
            if a_element:
                titles.append(a_element.string)
    
        return titles
    
    print get_stories(get_page())
    

    所以现在get_stories() 返回一个unicode 对象列表,它会按照您的预期打印出来。

    【讨论】:

      【解决方案3】:

      它工作正常,损坏的是输出。要么显式编码为你的控制台的字符集,要么找到不同的方式来运行你的代码(例如,从 IDLE 中)。

      【讨论】:

        猜你喜欢
        • 2017-08-03
        • 2013-06-20
        • 1970-01-01
        • 2014-07-14
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多