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