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

小编典典

_, 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)

通常,服务器可能会说谎或根本不报告编码(默认取决于内容类型),或者可能在响应正文中指定编码,例如html文档中的元素或xml文档的xml声明中的元素。作为最后的选择,可以从内容本身猜测编码。

您可以requests用来获取Unicode文本:

import requests # pip install requests

r = requests.get(url)

unicode_str = r.text # may use `chardet` to auto-detect encoding

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

from bs4 import BeautifulSoup # pip install beautifulsoup4

soup = BeautifulSoup(urllib2.urlopen(url)) # may use `cchardet` for speed

# ...

from bs4 import UnicodeDammit

dammit = UnicodeDammit(b"Sacr\xc3\xa9 bleu!")

print(dammit.unicode_markup)

# -> Sacré bleu!

print(dammit.original_encoding)

# -> utf-8

2021-01-20

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值