我需要存储可以使用任何语言的网站内容.我需要能够在内容中搜索Unicode字符串.
我尝试过类似的东西:
import urllib2
req = urllib2.urlopen('http://lenta.ru')
content = req.read()
Run Code Online (Sandbox Code Playgroud)
内容是一个字节流,所以我可以在其中搜索Unicode字符串.
我需要一些方法,当我这样做urlopen,然后阅读使用标题中的charset解码内容并将其编码为UTF-8.
我正在learnpythonthehardway进行练习41并继续得到错误:
Traceback (most recent call last):
File ".\url.py", line 72, in <module>
question, answer = convert(snippet, phrase)
File ".\url.py", line 50, in convert
result = result.replace("###", word, 1)
TypeError: Can't convert 'bytes' object to str implicitly
Run Code Online (Sandbox Code Playgroud)
我使用python3而书籍使用python2,所以我做了一些改动.这是脚本:
#!/usr/bin/python
# Filename: urllib.py
import random
from random import shuffle
from urllib.request import urlopen
import sys
WORD_URL = "http://learncodethehardway.org/words.txt"
WORDS = []
PHRASES = {
"class ###(###):":
"Make a class named ### that is-a ###.",
"class ###(object):\n\tdef __init__(self, ***)" :
"class ### has-a …Run Code Online (Sandbox Code Playgroud) 我有点惊讶的是,使用Python获取网页的charset非常复杂.我错过了一条路吗?HTTPMessage有很多函数,但不是这个.
>>> google = urllib2.urlopen('http://www.google.com/')
>>> google.headers.gettype()
'text/html'
>>> google.headers.getencoding()
'7bit'
>>> google.headers.getcharset()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: HTTPMessage instance has no attribute 'getcharset'
Run Code Online (Sandbox Code Playgroud)
所以你必须得到标题,并拆分它.两次.
>>> google = urllib2.urlopen('http://www.google.com/')
>>> charset = 'ISO-8859-1'
>>> contenttype = google.headers.getheader('Content-Type', '')
>>> if ';' in contenttype:
... charset = contenttype.split(';')[1].split('=')[1]
>>> charset
'ISO-8859-1'
Run Code Online (Sandbox Code Playgroud)
对于这样一个基本功能来说,这是一个惊人的步骤.我错过了什么吗?