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

我尝试过类似的事情:

import urllib2

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

内容是字节流,因此我可以在其中搜索 Unicode 字符串。

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

有帮助吗?

解决方案

执行完操作后,您将看到:

>>> 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-equiv 元标记)。

其他提示

要解析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">

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top