Python UTF-8 问题
这是我的脚本
# -*- coding: utf-8 -*-
from BeautifulSoup import BeautifulSoup
import urllib2
res = urllib2.urlopen('http://tazeh.net')
html = res.read()
soup = BeautifulSoup(''.join(html))
title = soup.findAll('title')
print title
当我在终端运行这个脚本时,出现了错误的文本,像这样
$ python test.py
[<title>ŮžŘ§ŰŒÚŻŘ§Ů‡ ŘŽŘ¨ŘąŰŒ ŘŞŘŮ„ŰŒŮ„ŰŒ تازه</title>]
这个标题是用UTF-8编码的,内容是波斯语
我刚开始学Python,出什么问题了?
2 个回答
1
使用 ''.join(html)
这个操作其实没必要,因为 html
这个变量本身已经是一个完整的字符串了。
不过,看起来这个页面的编码没有正确设置为 UTF-8。
3
如果我添加了(就像评论中建议的那样,在一个不太有用的地方):
html = html[:10000].decode("utf-8")
(这个切片是因为解码在页面更深的地方失败了)
之前:
soup = BeautifulSoup(html)
它打印出:
[<title>پایگاه خبری تحلیلی تازه</title>]