我正在使用 BeautifulSoup 从中提取新闻报道(仅标题)黑客新闻 http://news.ycombinator.com到现在为止就这么多了-
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')
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)