说明:个人学习python用。
操作系统:window10 x64
IDE:Pycharm 2017.2.2
Python版本:3.6.2
安装
pip3.6 install requests
或直接使用PyCharm安装即可
基本用法
import requests
1、简单请求
res = requests.get('http://www.httpbin.org')
print(res.text)
2、带参数的get请求
res = requests.get('http://www.httpbin.org/get', params={'username': 'cloudream'})
print(res.url)
print(res.text)
3、带参数、带请求头的post请求
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36'}
res = requests.post('http://www.ucai.cn/index.php?app=fullstack&mod=Public&act=doLogin',
data={'account': 'chen@ucai', 'password': '111111', 'remember': 'undefined'}, headers=None)
print(res.text)
4、二进制数据
import requests
from PIL import Image
from io import BytesIO
# 二进制数据
res = requests.get('https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1506308627&di=6327a7262a3254b8355557202ae418b8&imgtype=jpg&er=1&src=http%3A%2F%2Fscimg.jb51.net%2Fallimg%2F130104%2F2-130104091152C2.jpg')
img = Image.open(BytesIO(res.content))
img.save("c:/python_test/test.jpg")
5、json数据获取
res = requests.get('http://httpbin.org/get')
print(res.json())
6、post发送json数据
form = {'username': 'cloud', 'password': '123456'}
res = requests.post('http://httpbin.org/post', data=form)
print(res.text)
上述request如下:
POST http://httpbin.org/post HTTP/1.1
Host: httpbin.org
User-Agent: python-requests/2.18.4
Accept-Encoding: gzip, deflate
Accept: */*
Connection: keep-alive
Content-Length: 30
Content-Type: application/x-www-form-urlencoded
username=cloud&password=123456
而
res = requests.post('http://httpbin.org/post', data=json.dumps(form))
print(res.text)
的request如下:
POST http://httpbin.org/post HTTP/1.1
Host: httpbin.org
User-Agent: python-requests/2.18.4
Accept-Encoding: gzip, deflate
Accept: */*
Connection: keep-alive
Content-Length: 43
{"username": "cloud", "password": "123456"}