15. python requests

 


python requests

  • requests 是 Python 中一个非常流行的 HTTP 库,用于发送各种 HTTP 请求(如 GET、POST、PUT、DELETE 等)。它简单易用,功能强大,是处理网络请求的首选工具之一。以下是 requests 库的基本 API 和常见使用场景的介绍。

先了解HTTP基本概念

HTTP方法:常用的有GET、POST、PUT、DELETE等,分别对应不同的操作。比如GET用于获取资源,POST用于提交数据。
URL:统一资源定位符(Uniform Resource Locator),是访问资源的地址。
请求头(Headers):发送请求时可以包含的元数据,如用户代理、内容类型等。
请求体(Body):主要用于POST、PUT等请求,包含要发送的数据。
响应(Response):服务器返回的内容,包括状态码、响应头、响应体等。

示例:POST 请求

请求头:

  • 通常我们在发送请求时都需要带上请求头,请求头是将自身伪装成浏览器的关键,常见的有用的请求头如下
POST /api/login HTTP/1.1
Host: www.example.com
Content-Type: application/json
Content-Length: 48
Authorization: Bearer abc123xyz456
User-Agent: Mozilla/5.0

请求体:

{
  "username": "johndoe",
  "password": "secret123"
}

请求体详细信息说明:

字段 说明 常见值/示例
Content-Type 指定请求体的数据格式,告诉服务器如何解析请求体。 application/x-www-form-urlencoded(表单数据) application/json(JSON数据)
multipart/form-data(文件上传)
Content-Length 请求体的长度,单位为字节。 48
Authorization 用于身份验证,携带用户认证信息,如 token 或基本认证。 Bearer <token>
User-Agent 客户端的类型,标识发起请求的浏览器或应用。 Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko)
Chrome/91.0.4472.124 Safari/537.36
Accept 指定客户端可以处理的响应内容类型。 application/json
Cookie 客户端存储的 cookie,包含会话等信息。 session_id=abcd1234; user_id=xyz5678
请求体格式 请求体内容的格式。
application/x-www-form-urlencoded 表单数据格式,键值对以 & 分隔。 username=johndoe&password=secret123
multipart/form-data 用于文件上传,数据分为多个部分。 --boundary_string <br> Content-Disposition: form-data; name="file"; filename="example.txt"
application/json JSON 格式,常用于现代 Web API 通信。 {"username": "johndoe", "password": "secret123"}
text/plain 纯文本格式,适用于简单的文本数据。 Hello, this is a simple text message.

requests库的基本API

(1) 发送 GET 请求

  • GET 请求是最常用的 HTTP 方法,用于从服务器获取数据。

参数说明:

requests.get(url, params=None, **kwargs)
  • url:请求的 URL,必须是字符串。
  • params:(可选)一个字典或字节序列,表示查询字符串参数。如果提供字典,requests 会自动将其编码为查询字符串并附加到 URL 中。
  • \**kwargs:其他可选参数,如 headerscookiestimeout 等,这些参数与 requests.request() 方法的参数一致。

示例:

import requests

# 基本 GET 请求
response = requests.get('https://api.example.com/data')
print(response.json())  # 如果响应是 JSON 格式

# 带查询参数的 GET 请求
params = {'key1': 'value1', 'key2': 'value2'}
response = requests.get('https://api.example.com/data', params=params)
print(response.url)  # 打印完整的 URL,包含查询参数
print(response.text)  # 打印响应内容

# 添加自定义请求头
headers = {'User-Agent': 'MyApp/1.0'}
response = requests.get('https://api.example.com/data', headers=headers)
print(response.headers)  # 打印响应头

(2) 发送 POST 请求

  • POST 请求用于向服务器提交数据,通常用于表单提交或 API 调用。

参数说明

requests.post(url, data=None, json=None, **kwargs)
  • url:请求的 URL,必须是字符串。
  • data:(可选)一个字典、字节序列或文件对象,表示要发送的数据。如果提供字典,requests 会将其编码为 application/x-www-form-urlencoded 格式。
  • json:(可选)一个 Python 对象(如字典或列表),表示要发送的 JSON 数据。requests 会自动将其序列化为 JSON 格式。
  • headers:(可选)一个字典,包含发送的请求头信息。
  • \**kwargs:其他可选参数,如 cookiestimeout 等,这些参数与 requests.request() 方法的参数一致。

示例

import requests

# 基本 POST 请求(表单数据)
data = {'key1': 'value1', 'key2': 'value2'}
response = requests.post('https://api.example.com/submit', data=data)
print(response.text)  # 打印响应内容

# 发送 JSON 数据
json_data = {'name': 'Kimi', 'age': 25}
response = requests.post('https://api.example.com/submit', json=json_data)
print(response.json())  # 如果响应是 JSON 格式

# 添加自定义请求头
headers = {'Authorization': 'Bearer YOUR_ACCESS_TOKEN'}
response = requests.post('https://api.example.com/submit', json=json_data, headers=headers)
print(response.status_code)  # 打印 HTTP 状态码

datajson 的区别

  • data 用于发送表单数据,内容类型为 application/x-www-form-urlencoded
  • json 用于发送 JSON 数据,内容类型为 application/json

常用的响应处理方法:

# 常用的响应处理方法
print(response.status_code)  # 获取 HTTP 状态码
print(response.headers)  # 获取响应头
print(response.text)  # 获取原始文本内容
print(response.json())  # 如果响应是 JSON 格式,解析为字典
print(response.cookies)  # 获取响应中的 Cookies

钉钉机器人无人值守发送群消息:

#!/usr/bin/python3
#_*_coding:utf-8_*_
import requests
import json


def send_alter_to_dingding(webhook_url,content,keyword,title):
    headers = {"Content-Type": "application/json"}
    data = {
        "msgtype": 'markdown',
        "markdown": {
            "title": title,
            "text": f'# {title}\n\n{keyword}\n\n {content}',
        }
    }
    response = requests.post(webhook_url,headers=headers,data=json.dumps(data))
    if response.status_code == 200 and response.json().get("errcode") == 0:
        print("消息发送成功")
    else:
        print(f"消息发送失败: {response.json().get('errmsg')}")

webhook_url = "https://oapi.dingtalk.com/robot/send?access_token=your_token"  #your_token替换成钉钉机器人的token
keyword = 'shy'
title = "无人值守机器人消息:"
alter_content = "服务器繁忙"
send_alter_to_dingding(webhook_url,alter_content,keyword,title)
posted @   逃离这世界~  阅读(10)  评论(0编辑  收藏  举报
(评论功能已被禁用)
相关博文:
阅读排行:
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通
点击右上角即可分享
微信分享提示

目录导航