博客
关于我
Python requests模块
阅读量:801 次
发布时间:2023-03-06

本文共 3019 字,大约阅读时间需要 10 分钟。

请求模块简介

requests模块是一个第三方模块,用于在python环境中发送HTTP请求。与内置的urllib模块相比,requests模块更加简洁易用。以下是该模块的主要功能:

主要功能

  • 自动处理URL编码
  • 自动处理POST请求参数
  • 支持文件上传
  • 支持自动响应内容的编码
  • 实现持久连接(keep-alive)
  • 简化cookie和代理操作

基本使用步骤

  • 导入模块:import requests
  • 定义目标URL:url = 'https://www.baidu.com'
  • 发送请求:response = requests.get(url)
  • 提取响应信息:
    • 状态码:response.status_code
    • URL:response.url
    • 编码类型:response.apparent_encoding
    • 文本内容:response.textresponse.content.decode()
  • 请求方法

    requests模块提供多种请求方法,主要包括:

    常见请求属性

    • headers:请求头
    • cookies:请求cookie
    • timeout:设置响应超时时间
    • verify:是否验证证书

    响应对象

    每次请求都会返回一个response对象,包含以下信息:

    response.text与response.content的区别

    • response.text:类型str,自动解码响应内容,根据HTTP头部推测编码。
    • response.content:类型bytes,未指定编码。

    通过指定编码可以解决中文乱码问题:

    response.content.decode()  # 默认utf--8response.content.decode('gbk')  # 指定编码

    GET请求

    GET请求用于从服务器获取数据,常见格式如下:

    response = requests.get(url, params, args)

    参数说明

    • url:目标URL
    • params:GET请求参数
    • args:其他请求属性(如cookie、headers等)

    示例

  • 不带参数的GET请求:
  • url = 'https://www.baidu.com'response = requests.get(url)
    1. 带参数的GET请求:
    2. url = 'https://www.baidu.com/?p1=python&p2=java'response = requests.get(url)
      1. 通过字典传递参数(None键会被忽略):
      2. url = 'https://www.baidu.com'url_params = {'p1': 'python', 'p2': None, 'p3': 'java'}response = requests.get(url, url_params)

        POST请求

        POST请求用于向服务器提交数据,常见格式如下:

        response = requests.post(url, data={}, json={}, args)

        参数说明

        • url:目标URL
        • data:提交的字典、元组列表、文件或字节对象
        • json:提交的JSON对象
        • args:其他请求属性(如cookie、headers等)

        示例

      3. 表单参数的POST请求:
      4. url = 'https://www.baidu.com'payload = {'key1': 'value1', 'key2': None, 'key3': 'value3'}response = requests.post(url, data=payload)
        1. JSON参数的POST请求:
        2. url = 'https://www.baidu.com'payload = {"key1": "value1", "key2": None, "key3": 33}headers = {'content-type': 'application/json'}response = requests.post(url, json=payload, headers=headers)
          1. 添加请求属性参数:
          2. url = 'https://www.baidu.com'payload = {"key1": "value1", "key2": None, "key3": 33}headers = {'content-type': 'application/json'}cookies = {'testCookies_1': 'Hello_Python3', 'testCookies_2': 'Hello_Java'}response = requests.post(url, json=payload, headers=headers, cookies=cookies, timeout=5)

            会话请求(Session)

            requests模块中的Session类可以自动管理cookie,实现状态保持。其主要作用包括:

            • 自动处理cookie
            • 维护多次请求之间的状态

            示例

            import requestsheaders = {    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.87 Safari/537.36',    'content-type': 'application/json'}cookies = {    'testCookies_1': 'Hello_Python3',    'testCookies_2': 'Hello_Java'}data = {    'authenticity_token': 'authenticity_token',    'login': input('输入账号:'),    'password': input('输入密码:')}session = requests.session()# 请求1response1 = session.post('https://blog.csdn.net', data=data, headers=headers, cookies=cookies)print("==========session.post===========")print(response1.url)print(response1.request.body)print(response1.request.headers)print(response1.request._cookies)print(response1.cookies)# 请求2response2 = session.get('https://blog.csdn.net', headers=headers)print("==========session.get===========")print(response2.url)print(response2.request.body)print(response2.request.headers)print(response2.request._cookies)
    你可能感兴趣的文章
    python pandas从时间序列中提取唯一日期
    查看>>
    python pandas库详解_Pandas 库的详解和使用补充
    查看>>
    Python Pandas滚动聚合一列列表
    查看>>
    python pandas相关知识点(练习)
    查看>>
    Python Pandas,从.groupby().Apply()中的GROUP中分割行
    查看>>
    Python pathlib模块详解:优雅处理文件路径
    查看>>
    python Path模块的使用 glob iglob name
    查看>>
    python pickle 模块的使用
    查看>>
    Python PIL/Pillow-Pad图像至所需大小(例如,A4)
    查看>>
    python PIL模框使用
    查看>>
    Python ping 模块
    查看>>
    Python Pingouin:搞定各种假设检验和统计模型 !
    查看>>
    Python pip 国内镜像大全及使用办法
    查看>>
    Python输入输出练习,运算练习,turtle初步练习
    查看>>
    Python pip工具使用
    查看>>
    Python pip配置国内源
    查看>>
    Python Plotly 将轴数格式化为 %
    查看>>
    Redis 键值过期操作
    查看>>
    python predictabel_基于R语言PredictABEL包对Logistic回归模型外部验证
    查看>>
    Python psycopg2 超时
    查看>>