python 如何解析unicode变量_python – 如何使用BeautifulSoup将UTF-8编码的HTML正确解析为Unicode字符串?...

我正在运行一个获取UTF-8编码网页的

Python程序,并使用BeautifulSoup从HTML中提取一些文本.

但是,当我将文本写入文件(或在控制台上打印)时,会以意想不到的编码进行写入.

示例程序:

import urllib2

from BeautifulSoup import BeautifulSoup

# Fetch URL

url = 'http://www.voxnow.de/'

request = urllib2.Request(url)

request.add_header('Accept-Encoding', 'utf-8')

# Response has UTF-8 charset header,

# and HTML body which is UTF-8 encoded

response = urllib2.urlopen(request)

# Parse with BeautifulSoup

soup = BeautifulSoup(response)

# Print title attribute of a

which uses umlauts (e.g. können)

print repr(soup.find('div', id='navbutton_account')['title'])

运行这个结果:

# u'Hier k\u0102\u015bnnen Sie sich kostenlos registrieren und / oder einloggen!'

但是我会期待一个Python Unicode字符串将ö在单词können中渲染为\xf6:

# u'Hier k\xf6bnnen Sie sich kostenlos registrieren und / oder einloggen!'

我已经尝试将’fromEncoding’参数传递给BeautifulSoup,并尝试读取()和解码()响应对象,但它没有任何区别,也不会产生错误.

用命令curl www.voxnow.de | hexdump -C,我可以看到网页的ö字符确实是UTF-8编码(即它包含0xc3 0xb6):

20 74 69 74 6c 65 3d 22 48 69 65 72 20 6b c3 b6 | title="Hier k..|

6e 6e 65 6e 20 53 69 65 20 73 69 63 68 20 6b 6f |nnen Sie sich ko|

73 74 65 6e 6c 6f 73 20 72 65 67 69 73 74 72 69 |stenlos registri|

我超出了我的Python能力的限制,所以我对如何进一步调试感到失落.任何建议?

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值