zoukankan      html  css  js  c++  java
  • 网络编程之 requests 模块

    1. get 请求

    1 import requests
    2 url = 'http://api.xxxx.cn/api/user/stu_info?stu_name=xiaohei'
    3 data = {'stu_name':'小黑'}
    4 req = requests.get(url,params=data)    #发get请求
    5 print(req.json())
    6 print(type(req.json()))        #返回类型为:字典
    7 print(req.text)
    8 print(type(req.text))        #返回类型为:字符串的json串

    2. post 请求

    import requests
    url = 'http://api.xxxx.cn/api/user/login'
    data = {'username':'joseph','passwd':'aA123456'}
    req = requests.post(url,data)
    print(req.json())

    3. 上传文件

    import requests,json
    url = 'http://api.xxxx.cn/api/file/file_upload'
    #上传txt等格式
    # data = {
    #     'file':open('baidu.html',encoding='utf-8')
    # }        
    #上传图片格式
    data = {
        'file':open(r'C:UsersAdministratorDesktopjoseph.PNG','rb')
    }    
    
    req = requests.post(url,files = data)
    # print(req.json())    #返回成字典,
    # 如果报错,json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)
    #说明返回不成字典,要用req.text
    print(req.text)

    4. 入参为json类型

    import requests,random
    phone = random.randint(10000000000,99999999999)
    url = 'http://api.xxxx.cn/api/user/add_stu'
    data =  {
        "name":"joseph",
        "grade":"天蝎座",
        "phone":phone,
        "sex":"",
        "age":28,
        "addr":"河南省济源市北海大道32号"
      }
    req = requests.post(url,json=data)    #入参是json时,采用json=data
    print(req.json())

    5. 添加cookie

    import requests,random
    phone = random.randint(10000000000,99999999999)
    url = 'http://api.xxxx.cn/api/user/gold_add'
    data =  {
        "stu_id":468,
        "gold":178
      }        #传入的参数
    cookie = {'joseph':'337ca4cc825302b3a8791ac7f9dc4bc6'}    #cookie
    req = requests.post(url,data,cookies = cookie)
    print(req.json())

    6. 添加header

    import requests
    url = 'http://api.xxxx.cn/api/user/all_stu'
    header = {
        'Referer':'http://api.xxxx.cn/'
    }
    req = requests.get(url,headers= header)
    print(req.json())

    7. 下载图片

    import requests
    url = 'http://imgsrc.baidu.com/imgad/pic/item/9d82d158ccbf6c8154bdd5ccb63eb13533fa4008.jpg'
    req = requests.get(url)
    # res = req.content    #req.content返回的是二进制
    # print(res)
    fw = open('s.jpg','wb')
    fw.write(req.content)
     
     
     
  • 相关阅读:
    大数据测试2
    大数据测试3
    CROSS APPLY和 OUTER APPLY 区别详解
    SQL中的escape的用法
    Sql Server参数化查询之where in和like实现详解
    多行文本框换行符处理
    Cross Apply的用法
    交叉连接Cross Join的用法
    统计字符串中某个字符的个数
    JOIN用法
  • 原文地址:https://www.cnblogs.com/pengzhuopeng/p/9052963.html
Copyright © 2011-2022 走看看