zoukankan      html  css  js  c++  java
  • python--网络请求

    一、urllib模块

    from urllib.request import urlopen
    from urllib.parse import urlencode
    import json
    
    #get请求,不需要传参
    url ='http://www.nnzhp.cn/archives/423'
    res =urlopen(url).read().decode()  #获取到的内容为二进制类型的,decode()成字符串
    f=open('a.html','w',encoding='utf-8')
    f.write(res)
    f.close()
    
    #post请求,需传参,且参数必须是二进制
    url='http://api.nnzhp.cn/api/user/login'
    data ={'username':'niuhanyang','passwd':'aA123456'}
    res =urlopen(url,urlencode(data).encode()).read().decode()  #入参需要是二进制形式,所以要encode()
    d=json.loads(res)
    print(d)

    二、requests模块

    import requests
    
    url ='http://www.nnzhp.cn/archives/423'
    # 没有参数的get请求
    res=requests.get(url)
    
    #有参数的get请求,参数为k-v形式
    res=requests.get(url,
                     params={'key':'value'},
                     cookies={'key':'value'},
                     headers={'key':'value'})
    print(res.text)  #返回的是字符串
    
    
    url='http://api.nnzhp.cn/api/user/login'
    res=requests.post(url,
                      data={'username':'niuhanyang','passwd':'aA123456'})
    print(res.json()) #返回字典
    # print(res.text)#返回字符串
    
    #返回歌曲、图片.....(二进制文件)
    MP3_url='http://qiniuuwmp3.changba.com/1113525663.mp3'
    res = requests.get(MP3_url)
    mp3=res.content  #返回二进制
    f=open('g.mp3','wb')
    f.write(mp3)
    f.close()
    
    
    # 入参为file
    url='http://api.nnzhp.cn/api/file/file_upload'
    res=requests.post(url,files={'file':open('aa.txt','rb')})
    print(res.json())
    
    #入参为json
    url='http://api.nnzhp.cn/api/user/add_stu'
    data={'phone':'12345678654','age':2,'grade':'金牛座','name':'hehe'}
    res=requests.post(url,json=data)
    print(res.json())
  • 相关阅读:
    4QC(四象限变流器)
    SR锁存器
    JVM 专题二:虚拟机(二)Java虚拟机
    JVM 专题一:虚拟机(一)
    Scala 基础(一):各平台安装
    shell专题(十一):企业真实面试题(重点)
    shell专题(十):Shell工具(重点)
    shell专题(九):函数
    shell专题(八):read读取控制台输入
    shell专题(七):流程控制(重点)
  • 原文地址:https://www.cnblogs.com/HathawayLee/p/9904467.html
Copyright © 2011-2022 走看看