自学内容网 自学内容网

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)


原文地址:https://blog.csdn.net/bigcarp/article/details/142732538

免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!