Python获取网页编码的两种方法——requests、chardet

版权声明:本文为博主原创文章,注明出处,随意转载。 https://blog.csdn.net/IMW_MG/article/details/78783691

运行环境:Python3.6requests2.18.4

方法一:使用requests模块

In[2]: import requests
In[3]: res = requests.get('http://baidu.com')
In[4]: res
Out[4]: <Response [200]>
In[5]: res.encoding
Out[5]: 'ISO-8859-1'

方法二:使用chardet模块

In[2]: import chardet
In[3]: from urllib.request import urlopen
In[4]: url = 'http://www.baidu.com'
In[5]: html = urlopen(url).read()
In[6]: print(chardet.detect(html))
{'encoding': 'utf-8', 'confidence': 0.99, 'language': ''}

猜你喜欢

转载自blog.csdn.net/IMW_MG/article/details/78783691