zoukankan      html  css  js  c++  java
  • python学习笔记(十八)网络编程之requests模块

    上篇博客中我们使用python自带的urllib模块去请求一个网站,或者接口,但是urllib模块太麻烦了,传参数的话,都得是bytes类型,返回数据也是bytes类型,还得解码,想直接把返回结果拿出来使用的话,还得用json,发get请求和post请求,也不通,使用比较麻烦,还有一个比较方便的模块,比urllib模块方便很多,就是requests模块,它使用比较方便,需要安装,pip install requests即可,下面是requests模块的实例

    #1、发get请求
    url = 'http://api.python.cn/api/user/stu_info'
    data = {'stu_name':'小黑'}  #请求数据
    req = requests.get(url,params=data)  #发get请求
    print(req.json())  #返回数据是字典,但是要求必须返回的是json的时候,才能转为字典
    print(req.text)    #返回数据是string,json串

    #2 、发post请求
    url = 'http://api.python.cn/api/user/login'
    data = {'username':'test','passwd':'aA123456'} #请求数据
    req = requests.post(url,data) #发送post请求
    print(req.json())
    print(req.text)

    #3、入参是json类型的

    import random
    phone=random.randint(10000000000,99999999999)
    url='http://api.python.cn/api/user/add_stu'
    data = {
    "name":"小1",
    "grade":"天蝎座",
    "phone":phone,
    "sex":"男",
    "age":28,
    "addr":"河南省济源市北海大道32号"
    }
    req = requests.post(url,json=data)
    print(req.json())

    # 4、添加cookie
    url = 'http://api.python.cn/api/user/gold_add'
    data = {'stu_id':468,'gold':10000}
    djl = {'usertest':'337ca4cc825302b3a8791ac7f9dc4bc6'}
    req = requests.post(url,data,cookies=djl)
    print(req.json())

    #5、添加header
    url = 'http://api.python.cn/api/user/all_stu'
    header = {
    'Referer':'http://api.nnzhp.cn/'
    }
    req = requests.get(url,headers=header)
    print(req.json())

    #6、上传文件
    url= 'http://api.python.cn/api/file/file_upload'
    data = {
    'file':open(r'C:UsersjniuhanyangDesktop图6bd9026dt935575932465&690.jpg','rb')
    }
    req= requests.post(url,files=data)
    print(req.json())

    #7、下载文件
    url = 'http://up.mcyt.net/?down/46779.mp3' #下载图片、MP3、MP4都是同样的操作,找到该资源的url即可
    req = requests.get(url)
    print(req.content)#返回的是二进制模式
    fw = open('aaa.mp3','wb')#二进制的文件写模式是"wb",读模式是"rb"
    fw.write(req.content) #req.content返回的是bytes类型的
     
  • 相关阅读:
    BZOJ 2655: calc(拉格朗日插值)
    BZOJ 1485: [HNOI2009]有趣的数列(卡特兰数)
    [学习笔记] 关于组合数的一些总结
    CF 1076E Vasya and a Tree(线段树+树剖)
    CF 1082E Increasing Frequency(贪心)
    51nod 1149 Pi的递推式(组合数学)
    LOJ 2743(洛谷 4365) 「九省联考 2018」秘密袭击——整体DP+插值思想
    关于 unsigned int 比较大小
    洛谷 3295 [SCOI2016]萌萌哒——并查集优化连边
    洛谷 P4512 [模板] 多项式除法
  • 原文地址:https://www.cnblogs.com/mululu/p/9050059.html
Copyright © 2011-2022 走看看