【问题标题】:how to Unicode result in BeautifulSoup如何在 BeautifulSoup 中生成 Unicode
【发布时间】:2016-07-07 19:45:01
【问题描述】:

我尝试使用 BeautifulSoup 编写程序以向 (http://upodn.com/phon.php) 提交任何单词,然后打印结果。 例如,当我向 (http://upodn.com/phon.php) 网站提交“hello”字样时,结果是:həlo 但是当我使用我的脚本提交“你好”这个词时,结果是:həlo

我如何打印网站上出现的结果 => həlo

脚本:

#  -*- coding: utf-8 -*-

import mechanize
import cookielib
from BeautifulSoup import BeautifulSoup
import html2text

br = mechanize.Browser()
cj = cookielib.LWPCookieJar()
br.set_cookiejar(cj)
br.set_handle_equiv(True)
br.set_handle_redirect(True)
br.set_handle_referer(True)
br.set_handle_robots(False)
br.set_handle_refresh(mechanize._http.HTTPRefreshProcessor(), max_time=1)
br.addheaders = [('User-agent', 'Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.0.1) Gecko/2008071615 Fedora/3.0.1-1.fc9 Firefox/3.0.1'), ('Content-type', 'text/html; charset=utf-8')]
br.open('http://upodn.com/phon.php')
br.select_form(nr=0)
br.form['intext'] = 'hello'
br.submit()
data = br.response().read()
soup = BeautifulSoup(data)
# print soup
table = soup.find('table', {'rules': 'cols'})
result = []
for row in table.findAll("font"):
    d = row.text
    result.append(d)
print result[1]

输出:

həlo
[Finished in 2.7s]

【问题讨论】:

  • 首先,您使用的是过时版本的 BeautifulSoup;当前版本是包和模块bs4

标签: python python-2.7 unicode beautifulsoup mechanize


【解决方案1】:

您使用的是完全过时的 BeautifulSoup 版本,BeautifulSoup 3。当前版本 BeautifulSoup 4 在 PyPI 中称为 beautifulsoup4,并具有顶级包 bs4。 BeautifulSoup 4 解码这些 html 实体:

Python 2.7.10 (default, Oct 14 2015, 16:09:02) 
[GCC 5.2.1 20151010] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> from bs4 import BeautifulSoup
>>> print(BeautifulSoup('<b>h&#x0259;lo</b>').find('b').text)
həlo

编写使用 BeautifulSoup3 的新代码毫无意义,因此您现在应该切换。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2010-11-12
    • 2010-10-25
    • 2012-06-26
    • 1970-01-01
    • 1970-01-01
    • 2012-08-07
    • 1970-01-01
    相关资源
    最近更新 更多