当前位置: 首页 > article >正文

requests 中data=xxx、json=xxx、params=xxx 分别什么时候用

如果是要做爬虫模拟一个页面提交,看原页面是post还是get,以及Content-Type是什么。

  • GET 请求 使用 params=xxx,查询参数会被编码到 URL 中。
  • POST 请求,Content-Type为 application/x-www-form-urlencoded的,使用 data=xxx,(常见于直接 HTML 表单提交)。
  • POST 请求,Content-Type为 application/json的 使用 json=xxx,常见于通过ajax提交。
  • POST 请求,Content-Type为 multipart/form-data的,有上传文件,使用files=files, data=xxx (常见于直接 HTML 表单提交)

-------

  • 如果post请求同时传递 data 和 json 参数时,requests 库会自动忽略 data,并且只发送 json 中的数据作为请求体
  • post请求可以带params=xxx 这个参数。response = requests.post(url, json=json_data, params=xxx) 不会报错。
  • GET 请求不能带 json=json_data 参数。若使你尝试传递 json=json_data 参数,requests 库会忽略它

-------- 

如果multipart/form-data中一次请求上传多个文件,则

    files = {
        'file1': ('file1.jpg', file1, 'image/jpeg'),
        'file2': ('file2.jpg', file2, 'image/jpeg')
    }

GET 请求:

import requests

url = 'https://example.com/api'
params = {
    'name': 'John',
    'age': 30
}

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

 相当于get访问 URL:https://example.com/api?name=John&age=30

POST请求:application/x-www-form-urlencoded

import requests

url = 'https://example.com/api'
data = {
    'name': 'John',
    'age': 30
}

response = requests.post(url, data=data)

相当于直接网页提交表单

POST请求 application/json  (常见于AJAX提交)

import requests

url = 'https://example.com/api'
data = {
    'name': 'John',
    'age': 30
}

response = requests.post(url, json=data)

POST请求 multipart/form-data

import requests

url = 'https://acc.abc.com/api/home/UploadIDCard'

# 文件部分
file_path = 'path/to/your/file.jpg'
with open(file_path, 'rb') as file:
    files = {
        'Files': ('idcard_front.jpg', file, 'image/jpeg')  # (filename, file-object, mime-type)
    }

    # 其他参数部分
    data = {
        'name': 'John',
        'age': 30
    }

    # 发起POST请求
    response = requests.post(url, files=files, data=data)

import requests

url = 'https://example.com/upload'

# 打开多个文件
file1_path = 'path/to/your/file1.jpg'
file2_path = 'path/to/your/file2.jpg'

with open(file1_path, 'rb') as file1, open(file2_path, 'rb') as file2:
    files = {
        'file1': ('idcard_front.jpg', file1, 'image/jpeg'),
        'file2': ('idcard_back.jpg', file2, 'image/jpeg')
    }

    # 其他参数部分
    data = {
        'name': 'John',
        'age': 30
    }
    # 发起POST请求,上传多个文件
    response = requests.post(url, files=files, data=data)


http://www.kler.cn/news/343190.html

相关文章:

  • 做ppt用什么软件好?5个办公必备的ppt工具推荐!
  • VS Code最新版本Retome远程ssh不兼容旧服务器问题
  • 在Windows中使用谷歌浏览器观看和录制游戏直播
  • 【C#生态园】打造现代化跨平台应用:深度解析.NET桌面应用工具
  • c# gobal using
  • rdagent框架代码拆解:自动化因子挖掘
  • Java基础-Wrapper Classes(包装类)
  • Vulnhub靶场案例渗透[6]- DC6
  • JAVA基础面试题汇总(持续更新)
  • C++11 开发中的 Atomic 原子操作
  • react 封装防抖
  • 【优选算法】--- 分治 快速排序
  • 如何快速给word文件加拼音?请跟着步骤完成吧
  • centos7更新yum国内源
  • 【hot100-java】合并 K 个升序链表
  • 【含文档】基于Springboot+Vue的小区家政服务预约平台(含源码+数据库+lw)
  • CST软件优化超表面--- 偏振片- 线圆极化转换,天线阵任务,远场算轴比AR
  • 学习之偏函数
  • 数据挖掘学习笔记:朴素贝叶斯 | Python复现
  • 搬砖10、Python 图形用户界面和游戏开发