一、描述:
request模块是一个http处理模块,可以用来发起http请求和处理http回应。
二、使用
1.GET请求
(1)发送一个不带参数的get请求
r=request.get('http://www.baidu.com')
(2)发送一个带参数的get请求
get请求的参数用一个字典存储后使用params参数传入
dic={'key1':'value','key2':'value2'}
r=request.get('url',params=dic)
(3)定制请求头
请求头用一个字典存储后使用headers参数传入
dic_headers={
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:75.0) Gecko/20100101 Firefox/75.0',
'Accept-Encoding': 'gzip'
}
r=request.get('url',headers=dic_headers)
2.POST请求
服务器通过http请求头中的Content-Type字段来确定post数据使用何种编码(这里的编码是特指post数据类型)
(1)application/x-www-form-urlencoded------表单数据
x-www-form-urlencoded是POST数据的默认编码方式,一般通过html表单提交的POST数据都是这种编码方式
http请求:
Content-Type: application/x-www-form-urlencoded
Content-Length: 81
username=123&password=123&Login=Login
发送一个post表单请求:
使用字典存储请求数据后使用data参数传入
url = 'url/post'
dic_post = {
'key1': 'value1',
'key2': 'value2'
}
r = requests.post(url, data=dic_post)
(2)multipart/form-data-------文件上传
这种编码方式一般用来上传文件,form-data是上传的文件MIME类型
http请求:
Content-Type: multipart/form-data;
Content-Length: 441
Content-Disposition: form-data; name="uploaded"; filename="test.php"
<?php eval(@$_POST['a']); ?>
上传一个文件:
使用字典存储上传文件后使用files参数传入。需要使用open()函数打开文件
url = 'url/post'
file = {'file': open('test.txt', 'rb')}
r = requests.post(url, files=file)
3.response对象
在提交请求后,服务器将返回一个response对象,存储了页面信息,将返回的对象赋予参数 r
r.url #请求的URL
r.headers #服务器响应头(字典形式存储,键不区分大小写,若键不存在则返回None)
r.status_code #连接状态码
r.text #默认以unicode形式返回网页内容
r.content #以二进制返回网页内容(会自动解码 gzip 和 deflate 压缩)
r.json() #把网页中的json数据转成字典并将其返回
r.encoding #获取返回数据的编码
r.encoding = 'utf-8' #指定返回数据的编码