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类型的
     
  • 相关阅读:
    【思维】P5461 赦免战俘——两种有趣思路,分析推导
    雍正剑侠图人物关系图(2014-11-24 更新)思海整理
    h5 jq实现瀑布流
    jQuery省级联动
    jQuery 分页kkpager
    js jquery 常用函数集合
    h5 富文本编辑器
    向上取整,向下取整,四舍五入等
    前端常用的三大缓存
    jquery 跳转,刷新,返回,判断浏览器型号
  • 原文地址:https://www.cnblogs.com/mululu/p/9050059.html
Copyright © 2011-2022 走看看