新手学习python(十四)好用的模块requests
requests
是一个很实用的python HTTP客户端库,编写爬虫和测试服务器响应数据时经常会用到。可以说,Requests 完全满足如今网络的需求。支持python3
1、安装
A、通过pip安装 pip install requests
B、或者下载后安装
git clone git://github.com/kennethreitz/requests.git
cd requests
python setup.py install
导入 import requests
2、发送get请求
url = 'http://api.xxxxx.cn/api/user/stu_info'
data = { 'stu_name':'小黑'} #请求数据
req = requests.get(url, params = data) #发送get请求
print(req.json()) #返回的是json,转成字典类型
print(req.text) #返回string, json串
print(req.content) #打印的二进制内容
3、发送post请求
url = 'http://api.xxxx.cn/api/user/login'
data = { ‘username’:'niuxx','passwd':'xxxxxx' } #请求数据
req = requests.post( url,data ) #发送post请求
print( req.json() ) #返回操作结果
4、入参是json类型
import random
phone = random.randint(10000000000,99999999999)
url = 'http://api.xxxx.cn/api/user/add_stu'
data = {
"name":"xiaoz",
"grade":"天蝎座",
"phone":phone,
"sex":"男"
}
req = requests.post(url, json=data) #入参是json类型
print( req.json() )
5、添加cookie
url = 'http://api.xxxx.cn/api/user/gold_add'
data = { 'stu_id':466, 'gold':1000 }
cookie = { 'niuxxx':'384353495843bhn78n' }
req = requests.post(url,data,cookies=cookie) #添加cookie
print(req.json())
6、添加header
url = 'http://api.xxxx.cn/api/user/all_stu'
header={
'Referer':'http://api.xxxx.cn/'
}
req = requests.get(url, headers = header)
print(req.json())
6、上传文件
url = 'http://api.xxxx.cn/api/file/file_upload'
data = {
'file':open('笔记')
}
data = { 'file':open(r'D:\YYY.jpg','rb') } #上传图片,rb代表二进制读
req = requests.post(url,files=data)
print(req.json())
7、下载图片
url = 'http://www.xxxx.cn/wp-connect/uploads/2018/01/soup.jpg'
req = requests.get(url)
print( req.content) #返回图片的二进制内容
fw = open('s.jpg','wb') #wb代表图片的二进制的写
fw.write(req.content)