Requests 是用Python语言编写,基于 urllib,采用 Apache2 Licensed 开源协议的 HTTP 库。
它比 urllib 更加方便,可以节约我们大量的工作,完全满足 HTTP 测试需求。
1.GET请求
不带参数
import requests
print('==== get1 ====')
req = requests.get(url='https://movie.douban.com/chart')
print(req.status_code)
带参数
import requests
print('==== get2 ====')
req = requests.get(url='https://www.baidu.com/s', params={'wd': 'python'})
print(req.url)
print(req.text)
2.POST请求
import requests
import json
print('==== post ====')
req = requests.post('https://api.github.com/some/endpoint', data=json.dumps({'some': 'data'}))
print(req.json())
3.设置header头
import requests
print('==== header ====')
data = {'some': 'data'}
headers = {'Content-Type': 'application/json;charset=UTF-8',
'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36'}
req = requests.post('https://api.github.com/some/endpoint', data=data, headers=headers)
print(req.text)
4.上传文件
import requests
print('==== upload ====')
url = 'http://www.test.com/upload'
files = {'file': open('data/blur.jpg', 'rb')}
req = requests.post(url, files=files)
print(req.text)
5.设置Cookies
import requests
import json
print('==== cookies ====')
url = 'http://github.com'
cookies = {'name_cookie': 'xiao', 'age_cookie': '25'}
# 特殊符号都不能作为Cookie的内容
req = requests.get(url, cookies=cookies)
print(req.json())
print(req.cookies['name_cookie'])
6.设置请求超时
import requests
req = requests.get('http://github.com', timeout=0.001)
print(req.status_code)