• requests库


    一、安装库

    [root@node-2 ~]# pip3 install requests
    
    • 1

    二、request库的基本使用

    1.简单的get请求

    #!/usr/bin/python3
    import requests
    
    url = 'http://www.baidu.com'
    
    response = requests.get(url)
    print(response)
    print(response.status_code)
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8

    2.status_code状态码

    #这里response 的结果是状态码和准确的状态码
    [root@node-2 ~]# ./test.py 
    <Response [200]>
    200
    
    
    • 1
    • 2
    • 3
    • 4
    • 5

    3.text 返回结果参数

    此结果打印出来的中文乱码,如果字符集不是utf-8的就会乱码

    response = requests.get(url)
    response.encoding = 'utf-8'
    print(response.text)
    
    
    • 1
    • 2
    • 3
    • 4

    4.打印结果文本的字符集

    print (response.encoding)
    
    [root@node-2 ~]# ./test.py 
    ISO-8859-1
    
    • 1
    • 2
    • 3
    • 4

    5.content获取bytes类型的报文实体

    decode将content文本流转换成了utf-8.(解码)

    print (response.content.decode('utf-8'))
    
    • 1

    6.查看请求头

    print(response.request.headers)
    
    • 1

    7.封装请求头

    在本机安装了nginx服务。

    自定义了日志格式,这里引用了python客户端自定义的header name和age
    log_format  main '$remote_addr - $status - $http_user_agent $http_name $http_age';
    
    引用一下自定义格式的日志
    access_log logs/access.log main;
    
    • 1
    • 2
    • 3
    • 4
    • 5
    url = 'http://127.0.0.1'
    headers = {
            "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/92.0.4515.159 Safari/537.36",
            "name": "zhangsan",
            "age": "100"
    }
    response = requests.get(url,headers=headers)
    
    print(response.content.decode('utf-8'))
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9

    请求结果:这里看到了自定义封装的header头部中的3个参数

    127.0.0.1 - 200 - Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/92.0.4515.159 Safari/537.36 zhangsan 100
    127.0.0.1 - 200 - Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/92.0.4515.159 Safari/537.36 zhangsan 100
    127.0.0.1 - 200 - Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/92.0.4515.159 Safari/537.36 zhangsan 100
    
    • 1
    • 2
    • 3

    二、发送POST请求

    data就是传递给服务器的参数

    import requests
    
    url = 'http://127.0.0.1'
    
    params = {
            "username": "zhangsan",
            "password": "123"
    }
    
    response = requests.post(url,data=params)
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
  • 相关阅读:
    java毕业设计基于VUE电脑城摊位出租系统mybatis+源码+调试部署+系统+数据库+lw
    客路旅行(KLOOK)面试(部分)(未完全解析)
    pands使用openpyxl引擎实现EXCEL条件格式
    springboot源码理解十、自定义starter改造
    后端八股笔记------框架篇
    Python3 运算符
    混沌工程平台 ChaosBlade-Box 新版重磅发布
    Attentional Feature Fusion
    Springboot学习笔记
    Java InputStream如何读取文件呢?
  • 原文地址:https://blog.csdn.net/smile_pbb/article/details/126221013