python_requests模块

1、安装

pip install requests

2、get请求

如果需要加cookie可以直接加在headers中

import requests
#get请求带参数
url="http://xxx/api/user/stu_info"
data={"stu_name":"矿泉水1"}
result=requests.get(url,data)
print(result.json()) #返回字典类型
print(result.text) #返回一个字符串类型
print(result.content) #返回bytes类型

#get请求无参数
url2='http://q4.qlogo.cn/g?b=qq&nk=xxx&s=140'
result2=requests.get(url2)
fw=open("jjj.png",'wb') #get请求结果写入文件
fw.write(result2.content)
fw.close()

 3、post 请求

 

1、传入xml格式文本

requests.post(url='',data='<?xml  ?>',headers={'Content-Type':'text/xml'})



2、传入json格式文本

requests.post(url='',data=json.dumps({'key1':'value1','key2':'value2'}),headers={'Content-Type':'application/json'})

或者:

requests.post(url='',json={{'key1':'value1','key2':'value2'}},headers={'Content-Type':'application/json'}


3、请求正文是multipart/form-data

除了传统的application/x-www-form-urlencoded表单,我们另一个经常用到的是上传文件用的表单,这种表单的类型为multipart/form-data

requests.post(url='',data={'key1':'value1','key2':'value2'},headers={'Content-Type':'multipart/form-data'})

4、请求正文是application/x-www-form-urlencoded
默认就是这种,可以不标注headers的值 requests.post(url
='',data={'key1':'value1','key2':'value2'},headers={'Content-Type':'application/x-www-form-urlencoded'})

 

import requests

#application/x-www-form-urlencoded格式
url='http://xxx/api/user/login' #地址
data={'username':'niuhanyang','passwd':'aA123456'} #传参
result=requests.post(url,data) #发送POST请求
print(result.text) #打印结果

#application/json 格式
url4="http://xxx/api/user/add_stu"
header2={'Content-Type':'application/json'} #
data={
        "name":"小黑324",
        "grade":"天蝎座",
        "phone":13512532945,
        "sex":"",
        "age":28,
        "addr":"河南省济源市北海大道32号"
      }
result4=requests.post(url4,json=data,headers=header2)
print(result4.text)

#application/soap+xml 格式
url2="http://www.webxml.com.cn/WebServices/WeatherWebService.asmx"
header={'Content-Type':'application/soap+xml'} #
data=r'''<?xml version="1.0" encoding="utf-8"?>
<soap12:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" 
xmlns:soap12="http://www.w3.org/2003/05/soap-envelope"><soap12:Body><getWeatherbyCityName xmlns="http://WebXml.com.cn/">
<theCityName>北京</theCityName></getWeatherbyCityName></soap12:Body></soap12:Envelope>'''
result2=requests.post(url2,data=data.encode('utf-8'),headers=header)
print(result2.text)


#上传文件
url3='http://xxx/api/file/file_upload'
result3=requests.post(url3,files={'file':open('x.jpg','rb')}) #上传文件需要用二进制方式进行打开
print(result3.text)

 

posted @ 2019-07-02 14:58  小戳同学  阅读(259)  评论(0编辑  收藏  举报