python - 如何避免内容的显式解码?

标签 python unicode urllib2

我知道 .encode('utf-8') 是必要的。

# -*- coding: utf-8 -*-
import urllib2
url = u'https://fr.wikipedia.org/wiki/Nîmes'
response = urllib2.urlopen(url.encode('utf-8'))
content = response.read().decode('utf-8')
print type(content)

但是如何避免 .decode('utf-8') ?毕竟,相关页面在 header 中正确声明了其编码。

最佳答案

您可以使用requests :

# -*- coding: utf-8 -*-

import requests
url = u'https://fr.wikipedia.org/wiki/Nîmes'
response = requests.get(url)
content = response.content
text = response.text
assert type(content) == str
assert type(text) == unicode

关于python - 如何避免内容的显式解码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35783473/

相关文章:

java - 如何将 unicode hex "0x20000"的字符串表示形式转换为 Java 中的 int 代码点 0x20000

python urllib2 和 unicode

python - 当 URL 存在时 urllib2 捕获 404 错误

python - 在 Python unicode 字符串中删除重音(规范化)的最佳方法是什么?

java - 由于字符常量无效,Android 应用程序无法编译

python - 使用Python urllib2网站表单登录

Python - Django - 'InMemoryUploadedFile' 对象没有属性 'split'

python - 如何使用 pip install 修复 'Command errored out with exit status 1'

python - Atlassian Bamboo 如何识别 python pytest 报告

python - 当多个 URL 具有相同名称时使用 django reverse()