request模块发送http请求,获取响应。
request模块安装方式:
pip install requests
pip3 install requests
利用模块发送get请求
import requests
url = 'http://www.baidu.com/'
response = requests.get(url)
# text-打印源码
print(response.text)
发现乱码,修改代码
乱码原因text推测解码错误
import requests
url = 'http://www.baidu.com/'
response = requests.get(url)
print(response.encoding)
response.encoding = 'utf8'
# text-打印源码
print(response.text)
print(response.encoding)
或者
由于 response.content.decode('推测编码格式')=response.text
import requests
url = 'http://www.baidu.com/'
response = requests.get(url)
print(response.encoding)
# text-打印源码
print(response.content.decode('utf8'))
print(response.encoding)
这个方法 response.encoding 没变化
import requests
url = 'http://www.baidu.com/'
response = requests.get(url)
print(response.encoding)
# 存储byte类型的响应源码 二进制类型数据 可以decode(解码)
print(response.content)
print(response.encoding)
\xe7\x99\xbe\xe5
如果还乱码,可尝试
乱码
utf-8
gbk
gb2312
ascii
iso-8859-1 都不行就用byte方式
UnicodeDecodeError: 'gbk' codec can't decode
可能是要处理的字符串本身不是gbk编码,但是却以gbk编码去解码 。比如,字符串本身是utf-8的,但是却用gbk去解码utf-8的字符串,所以结果不用说,则必然出错
python里所有的变量都是对象