相关疑难解决方法(0)

urllib2读取为Unicode

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

我尝试过类似的东西:

import urllib2

req = urllib2.urlopen('http://lenta.ru')
content = req.read()
Run Code Online (Sandbox Code Playgroud)

内容是一个字节流,所以我可以在其中搜索Unicode字符串.

我需要一些方法,当我这样做urlopen,然后阅读使用标题中的charset解码内容并将其编码为UTF-8.

python unicode urllib2

46
推荐指数
2
解决办法
6万
查看次数

Python3错误:TypeError:无法隐式地将'bytes'对象转换为str

我正在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 type-conversion typeerror object-to-string

39
推荐指数
2
解决办法
9万
查看次数

获取网页字符集的好方法,可靠的简短方法是什么?

我有点惊讶的是,使用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)

对于这样一个基本功能来说,这是一个惊人的步骤.我错过了什么吗?

python content-type http

14
推荐指数
2
解决办法
5056
查看次数