zoukankan      html  css  js  c++  java
  • python之urllib模块和requests模块

    一、urllib模块

    python标准库自带的发送网络请求的模块。

    # 用python怎么打开浏览器,发送接口请求
    import urllib
    from urllib.request import urlopen
    from urllib.parse import urlencode
    # url="http://www.nnzhp.cn/archives/527"
    # res=urlopen(url).read()#返回的数据是二进制类型,怎么转换成字符串?,其实就是get请求
    # print(res.decode())#encode()转换成二进制,decode()转换成字符串
    # f=open('a.html','w',encoding='utf-8')#打开一个文件
    # f.write(res.decode())#将网站上请求到的数据写入到文件中
    # f.close()
    
    url="http://api.nnzhp.cn/api/user/login"
    data={"username":"niuhanyang","passwd":"aA123456"}
    data=urlencode(data)#将参数拼接起来,username=niuhanyang&passwd=aA123456
    res=urlopen(url,data.encode()).read()
    print(res.decode())
    
    import json
    import jsonpath
    # 从接口数据中获取某个字段值,从json文件中获取数据,loads()将字符串转换成字典类型
    dict=json.loads(res.decode())
    print(dict)
    # print(dict['login_info']['sign'])
    # print(jsonpath.jsonpath(dict,expr='$.[login_info].[sign]'))
    print(jsonpath.jsonpath(dict,expr='$..sign'))#不管字典有多少层,获取到字典中的值

    二、requests模块

    requests模块是基于urllib模块开发,用于发送http请求。

    import requests
    #向接口发送请求,获取返回的数据
    #get请求
    # url="http://XXXX/api/user/stu_info"
    # data={'stu_name':'lyh'}
    # res=requests.get(url,params=data,cookies={'k1':'v1','k2':'v2'},headers={'kk1':'vv1','kk2':'vv2'})
    # print(res.text)
    
    #post请求
    url="XXX/api/user/login"
    data={"username":"liuyihan","passwd":"aA123456"}
    res=requests.post(url,params=data)
    print(res.json())#返回的是一个字典
    print(res.text)#返回的是一个字符串
    
    url="XXX/api/file/file_upload"
    res=requests.post(url,files={'file':open('a.html','rb')})
    print(res.json)
  • 相关阅读:
    request-log-analyzer日志分析
    ubuntu下git输出的颜色变化
    vundle安装 给vim插上翅膀
    安装ruby
    【HDU1944】S-Nim-博弈论:SG函数
    【HDU1944】S-Nim-博弈论:SG函数
    我对SG函数的理解
    我对SG函数的理解
    【POJ2154】Color-Polya定理+欧拉函数
    【POJ2154】Color-Polya定理+欧拉函数
  • 原文地址:https://www.cnblogs.com/balllyh/p/10398388.html
Copyright © 2011-2022 走看看