栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

在Python中获取HTTP响应的字符集/编码的好方法

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

在Python中获取HTTP响应的字符集/编码的好方法

要解析http标头,您可以使用

cgi.parse_header()

_, params = cgi.parse_header('text/html; charset=utf-8')print params['charset'] # -> utf-8

或使用响应对象:

response = urllib2.urlopen('http://example.com')response_encoding = response.headers.getparam('charset')# or in Python 3: response.headers.get_content_charset(default)

通常,服务器可能会说谎或根本不报告编码(默认取决于内容类型),或者可能在响应正文中指定编码,例如

<meta>
html文档中的元素或xml文档的xml声明中的元素。作为最后的选择,可以从内容本身猜测编码。

您可以

requests
用来获取Unipre文本:

import requests # pip install requestsr = requests.get(url)unipre_str = r.text # may use `chardet` to auto-detect encoding

BeautifulSoup
解析html(并转换为Unipre作为副作用):

from bs4 import BeautifulSoup # pip install beautifulsoup4soup = BeautifulSoup(urllib2.urlopen(url)) # may use `cchardet` for speed# ...

bs4.UnipreDammit
直接获取任意内容(不一定是html):

from bs4 import UnipreDammitdammit = UnipreDammit(b"Sacrxc3xa9 bleu!")print(dammit.unipre_markup)# -> Sacré bleu!print(dammit.original_encoding)# -> utf-8


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/380991.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号