关于python:爬虫使用requests发送post请求示例

5次阅读

共计 1995 个字符,预计需要花费 5 分钟才能阅读完成。

简介

HTTP 协定规定 post 提交的数据必须放在音讯主体中,然而协定并没有规定必须应用什么编码方式。服务端通过是依据申请头中的 Content-Type 字段来获知申请中的音讯主体是用何种形式进行编码,再对音讯主体进行解析。具体的编码方式包含:

application/x-www-form-urlencoded 最常见 post 提交数据的形式,以 form 表单模式提交数据。
application/json 以 json 串提交数据。
multipart/form-data 个别应用来上传文件。

一、以 form 表单发送 post 申请

Reqeusts 反对以 form 表单模式发送 post 申请,只须要将申请的参数结构成一个字典,而后传给 requests.post()的 data 参数即可。
例:

# -*- coding: utf-8 -*-
# author:Gary
import requests

url = 'http://httpbin.org/post'  # 一个测试网站的 url
data = {'key1': 'value1', 'key2': 'value2'}  # 你发送给这个的数据
r = requests.post(url, data=data)  # 应用 requests 的 post 办法,data 承受你想发送的数据
print(r.text)  # 查看返回的内容

输入
外汇 MT4 教程 https://www.kaifx.cn/mt4.html

{“args”: {},“data”:“”,“files”: {}, 
 #你提交的表单数据“form”: {“key1”:“value1”,“key2”:“value2”},“headers”: { 
……“Content-Type”:“application/x-www-form-urlencoded”, 
…… 
},“json”: null, 
…… 
}

能够看到,申请头中的 Content-Type 字段已设置为 application/x-www-form-urlencoded,且 data = {‘key1’:‘value1’,‘key2’:‘value2’}以 form 表单的模式提交到服务端,服务端返回的 form 字段即是提交的数据。

二、以 json 模式发送 post 申请

能够将一 json 串传给 requests.post()的 data 参数,

# -*- coding: utf-8 -*-
# author:Gary
import requests
import json

url = 'http://httpbin.org/post'  # 一个测试网站的 url
json_data = json.dumps({'key1': 'value1', 'key2': 'value2'})  # 你发送给这个的数据, 数据格式转为 json
r = requests.post(url, data=json_data)  # 应用 requests 的 post 办法,data 承受你想发送的数据
print(r.text)  # 查看返回的内容

输入:

{“args”: {},“data”:“{\”key2\”: \”value2\”, \”key1\”: \”value1\”}”,“files”: {},“form”: {},“headers”: { 
……“Content-Type”:“application/json”, 
…… 
},“json”: {“key1”:“value1”,“key2”:“value2”}, 
…… 
}

能够看到,申请头的 Content-Type 设置为 application/json,并将 json_data 这个 json 串提交到服务端中。

三、以 multipart 模式发送 post 申请(上传文件)

Requests 也反对以 multipart 模式发送 post 申请,只需将一文件传给 requests.post()的 files 参数即可。

# -*- coding: utf-8 -*-
# author:Gary
import requests

url = 'http://httpbin.org/post'
files = {'file': open('report.txt', 'rb')}  # 目录下得有 report.txt 文件能力上传,rb 是指以二进制格局关上一个文件用于只读。r = requests.post(url, files=files)  # 通过 files 参数指定你想发送的文件的内容
print(r.text)

输入:

{“args”: {},“data”:“”,“files”: {“file”:“Hello world!”},“form”: {},“headers”: {……“Content-Type”:“multipart/form-data; boundary=467e443f4c3d403c8559e2ebd009bf4a”, 
…… 
},“json”: null, 
…… 
}

文本文件 report.txt 的内容只有一行:Hello world!,从申请的响应后果能够看到数据已上传到服务端中。

正文完
 0