Phobia. 2021-06-18 22:16 采纳率: 100%
浏览 18
已采纳

python中的requests库如何使用

 

  • 写回答

2条回答 默认 最新

  • 小P聊技术 2021-06-18 22:37
    关注

    Python3中request库的使用(爬虫基础):https://blog.csdn.net/baidu_41871794/article/details/83904024

    • request库基于urllib,比urllib更加方便,是Python更加简单的http库。
    • 使用request库的一个例子:
    import requests
    response = requests.get('http://www.baidu.com')
    print(type(response))#返回值的类型
    print(response.status_code)#当前网站返回的状态码
    print(type(response.text))#网页内容的类型
    print(response.text)#网页的具体内容(html代码)
    print(response.cookies)#网页的cookie
    

    具体解释写在了注释里面,request中输出网页的html代码的方法是response.text方法,它相当于urllib库的response.read方法,只不过不需要进行decode操作。
    打印cookie的操作也比urllib简单,只需要使用.cookie方法即可。
    执行结果如下:
    在这里插入图片描述

    • 各种请求方式
    import requests
    
    requests.post('http://httpbin.org/post')
    requests.delete('http://httpbin.org/delete')
    requests.put('http://httpbin.org/put')
    requests.head('http://httpbin.org/get')
    requests.options('http://httpbin.org/get')
    

    这里的请求返回值可以去http://httpbin.org获取,这个网站可以用来进行http请求的测试。

    GET请求

    • 基本的GET请求
    import requests
    response = requests.get('http://httpbin.org/get')
    print(response.text)
    

    这是request中最简单的get请求。

    • 带参数的GET请求
    import requests
    response = requests.get('http://httpbin.org/get?name=germey&age=22')
    print(response.text)
    

    其中http://httpbin.org/get后面的部分为get方法的基本构成,不清楚的可以去了解一下,以上代码会返回get请求参数。

    如果不想构造url,那么requeat库中有一个params参数,可以传入一个字典,他会给你自动拼接到url后面,例子如下:

    import requests
    data = {
        'name':'germey',
        'age':'22'
    }
    response = requests.get('http://httpbin.org/get',params=data)
    print(response.text)
    

    这样就能构造一个get请求参数,和上面返回的内容相同。

    • 解析json
    
    import requests
    import json
    response = requests.get('http://httpbin.org/get')
    print(type(response.text))
    print(response.json())
    print(json.loads(response.text))
    print(response.text)
    print(type(response.json()))
    

    response.json()与json.loads ()返回的结果完全相同,在使用ajax请求时比较常用。

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 PSCAD安装问题 ERROR: Visual Studio 2013, 2015, 2017 or 2019 is not found in the system.
  • ¥15 (标签-MATLAB|关键词-多址)
  • ¥15 关于#MATLAB#的问题,如何解决?(相关搜索:信噪比,系统容量)
  • ¥500 52810做蓝牙接受端
  • ¥15 基于PLC的三轴机械手程序
  • ¥15 多址通信方式的抗噪声性能和系统容量对比
  • ¥15 winform的chart曲线生成时有凸起
  • ¥15 msix packaging tool打包问题
  • ¥15 finalshell节点的搭建代码和那个端口代码教程
  • ¥15 Centos / PETSc / PETGEM