这是我的脚本
# -*- 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新手,出了什么问题?
最佳答案
如果我添加(就像建议在不太有用的地方做的评论之一):
html = html[:10000].decode("utf-8")
(切片是因为解码在页面更远的偏移处失败)
之前:
soup = BeautifulSoup(html)
它打印:
[<title>پایگاه خبری تحلیلی تازه</title>]
关于python utf-8问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6749890/