python - 具有类属性的 BeautifulSoup findall-unicode 编码错误

标签 python beautifulsoup

我正在使用 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)

我如何让它工作?

最佳答案

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

print some_unicode_string.decode('utf-8')

关于python - 具有类属性的 BeautifulSoup findall-unicode 编码错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5746888/

相关文章:

python - 选择除 BeautifulSoup 中具有某些类的所有 div

python - 使用 Python 访问 Web 表 - NIST 网站

python - 使用排除时用户对象不可迭代

Python:删除非字母单词

python - 将我的设置更改为 DEBUG = False 后发生的错误

python - BeautifulSoup - 解析不返回预期的标签

python - 如何抓取另一个 html 行后面的特定 html 行

python mysqldb 打印文本,即使代码中没有打印语句

python - matplotlib,如何压缩x轴的部分

python - 使用 Beautifulsoup4 从 HTML 中去除 Doctype?