获取剩余可用字符集python_在Python中获取HTTP响应的字符集/编码的好方法

如果您碰巧熟悉Flask/Werkzeugweb开发堆栈,那么您将很高兴知道Werkzeug库对这种HTTP头解析有一个确切的答案,并解释了内容类型根本没有指定的情况,正如您所希望的那样。>>> from werkzeug.http import parse_options_header

>>> import requests

>>> url = 'http://some.url.value'

>>> resp = requests.get(url)

>>> if resp.status_code is requests.codes.ok:

... content_type_header = resp.headers.get('content_type')

... print content_type_header

'text/html; charset=utf-8'

>>> parse_options_header(content_type_header)

('text/html', {'charset': 'utf-8'})

所以你可以:>>> content_type_header[1].get('charset')

'utf-8'

请注意,如果不提供charset,则会生成:>>> parse_options_header('text/html')

('text/html', {})

如果您只提供空字符串或dict,它甚至可以工作:>>> parse_options_header({})

('', {})

>>> parse_options_header('')

('', {})def parse_options_header(value):

"""Parse a ``Content-Type`` like header into a tuple with the content

type and the options:

>>> parse_options_header('text/html; charset=utf8')

('text/html', {'charset': 'utf8'})

This should not be used to parse ``Cache-Control`` like headers that use

a slightly different format. For these headers use the

:func:`parse_dict_header` function.

...

希望有一天能帮上忙!:)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值