2009-06-20 69 views
45

我需要存储可以使用任何语言的网站的内容。我需要能够在内容中搜索Unicode字符串。urllib2读取为Unicode

我已经试过类似:

import urllib2 

req = urllib2.urlopen('http://lenta.ru') 
content = req.read() 

的内容是字节流,这样我就可以搜索它的Unicode字符串。

我需要某种方式,当我做urlopen,然后阅读使用标题中的字符集来解码内容并将其编码为UTF-8。

+0

编码是使用urllib库中的函数完成的,而不是从urllib2完成的。从http://www.voidspace.org.uk/python/articles/urllib2.shtml#headers – Macarse 2009-06-20 03:55:36

+1

@Macarse这不是Vitaly提到的编码,他指的是解码和编码实际的请求上下文与'[字节字符串]'。decode('[charset]')和u'[unicode string]'encode('utf-8')。您指的是编码请求参数。 – 2012-05-08 13:57:38

回答

96

您执行操作后,你会看到:

>>> req.headers['content-type'] 
'text/html; charset=windows-1251' 

等:

>>> encoding=req.headers['content-type'].split('charset=')[-1] 
>>> ucontent = unicode(content, encoding) 

ucontent现在是一个Unicode字符串(的140655个字符) - 例如要显示它的一部分,如果你的终端是UTF-8的话:

>>> print ucontent[76:110].encode('utf-8') 
<title>Lenta.ru: Главное: </title> 

你可以搜索等等等等

编辑:Unicode I/O通常很棘手(这可能是什么阻止了原始提问者),但我要绕过输入Unicode字符串到交互式Python解释器的难题(与原始问题完全无关)来展示一旦一个Unicode字符串被正确输入(我是通过代码点来完成的 - 愚蠢但并不棘手;-),搜索绝对是一件容易的事情(因此希望最初的问题已被彻底解答)。再次假定UTF-8终端:

>>> x=u'\u0413\u043b\u0430\u0432\u043d\u043e\u0435' 
>>> print x.encode('utf-8') 
Главное 
>>> x in ucontent 
True 
>>> ucontent.find(x) 
93 

注意:请记住,这种方法可能并不适用于所有网站的工作,因为有些网站只指定提供的文档中的字符编码(使用HTTP-当量meta标签, 例如)。

9

为了解析Content-Type HTTP头,你可以使用cgi.parse_header功能:

import cgi 
import urllib2 

r = urllib2.urlopen('http://lenta.ru') 
_, params = cgi.parse_header(r.headers.get('Content-Type', '')) 
encoding = params.get('charset', 'utf-8') 
unicode_text = r.read().decode(encoding) 

另一种方式来获得该字符集:

>>> import urllib2 
>>> r = urllib2.urlopen('http://lenta.ru') 
>>> r.headers.getparam('charset') 
'utf-8' 

或者在Python 3:

>>> import urllib.request 
>>> r = urllib.request.urlopen('http://lenta.ru') 
>>> r.headers.get_content_charset() 
'utf-8' 

字符编码也可以在html文档中指定,例如<meta charset="utf-8">