# from urllib import request
# from urllib.parse import urlencode #把字典转换成stu_name=&%¥#¥%%¥#这种形式
# url = 'http://api.nnzhp.cn/api/user/stu_info'
# data = {'stu_name':'小黑'}
# str_data = urlencode(data) #把字典转换成stu_name=&%¥#¥%%¥#这种形式
# result = request.urlopen(url+'?'+str_data).read() #get请求
# request.urlopen(url,data=str_data.encode().read() #post请求
# print(result.decode())
# bytes类型变字符串 :decode()
# 字符串变bytes类型 :encode()
import requests
url = 'http://api***************'
get请求:
req = requests.get(url,params={'stu_name':'abc'}) #参数不是必填
print(req.json()) #返回的json直接帮你转成字典
print(req.text) #返回的就是字符串,打开一个网页,如果返回的不是json的话,就要用它
print(req.status_code)#返回的http状态码
print(req.content) #返回的bytes类型的,下载文件时候用它
post请求:
url = 'http://api.*****************'
req1 = requests.post(url,data={'username':'niuhanyang','password':'aA123456'})
print(req1.json())
发送header ,cookie
两种方式传kookie
①kookie
url = 'https://qun**************'
data = {'bkn':'577478518'}
s = ''' #cookie转成字典
pgv_info=ssid=s8613512240; pgv_pvid=2253949531; _qpsvr_localtk=0.3734522608298185; pgv_pvi=5672155136; pgv_si=s9849359360; uin=o1031884559; skey=@VXMapbFK2; RK=4TjNdoFSSk; ptcz=369c17e9df1bba325bd18f5857144a19af12bad1fc4d9d7c465c44abae39f718; p_uin=o1031884559; pt4_token=gUjd0eGAiZoFj0qPn3bXuw2OuKLR0-vDCYacDzQiNvU_; p_skey=6Lt2XFvZYP8SmRHjFYdzQVmCyk-sbvcCE-j8SeK1Uzs_; traceid=a878c98309
'''
d = {}
for c in s.split(';'):
k,v = c.strip().split('=')
d[k] = v
print(d)
req = requests.post(url,data,cookies=d)
②header
header = {'cookie':'pgv_info=ssid=s8613512240; ****************************)
print(req.json())
钉钉机器人
url = 'https://oapi.dingtalk.com/robot/send?access_token=***************************************'
today = datetime.datetime.now()
d = {"msgtype": "text","text": {"content": "111"}}
req = requests.post(url,json=d)
print(req.json())
print(req.cookies)#有登录接口,怎么获取cookie
下载文件:
url = 'https://q4.q******************'
req = requests.get(url)
f = open('xx.jpg','wb')
f.write(req.content)
f.close()
上传文件:
url = 'http://api.****************'
f = open('xx.jpg','rb')
data = {'file':f}
r = requests.post(url,files=data)
r.json()
f.close()