Http
requests 是 Python 的 Http 请求库,AScript 中内置了这个库
# 导包
import requests
GET 请求
基本 GET 请求
import requests
r = requests.get("http://www.baidu.com")
# 打印状态码
print(r.status_code)
# 打印返回文本
print(r.text)
带参数的 GET 请求
import requests
# 方式1: 参数拼在 URL 中
r = requests.get("https://httpbin.org/get?name=airscript&version=3.3")
print(r.text)
# 方式2: 通过 params 传参 (推荐)
params = {"name": "airscript", "version": "3.3"}
r = requests.get("https://httpbin.org/get", params=params)
print(r.json())
GET 请求返回 JSON
import requests
r = requests.get("http://www.weather.com.cn/data/sk/101010100.html")
r.encoding = r.apparent_encoding
obj = r.json()
print(obj['weatherinfo']['city'])
POST 请求
Form 表单提交
import requests
r = requests.post("https://httpbin.org/post", data={"user": "test", "pwd": "123"})
print(r.text)
JSON 提交
import requests
# 推荐: 直接使用 json 参数, 自动序列化和设置 Content-Type
r = requests.post("https://httpbin.org/post", json={"key1": "value1", "key2": "value2"})
print(r.json())
上传文件
import requests
from ascript.android.system import R
# 上传单个文件
files = {"file": open(R.res("1.png"), "rb")}
r = requests.post("https://httpbin.org/post", files=files)
print(r.status_code)
import requests
from ascript.android.system import R
# 上传文件同时附带表单参数
files = {"file": ("image.png", open(R.res("1.png"), "rb"), "image/png")}
data = {"description": "测试图片"}
r = requests.post("https://httpbin.org/post", files=files, data=data)
print(r.text)
其他请求方法
import requests
# PUT 请求
r = requests.put("https://httpbin.org/put", json={"key": "value"})
# DELETE 请求
r = requests.delete("https://httpbin.org/delete")
# PATCH 请求
r = requests.patch("https://httpbin.org/patch", json={"key": "new_value"})
请求头设置
自定义 Headers
import requests
headers = {
"User-Agent": "AScript/3.3",
"Authorization": "Bearer your_token_here",
"Content-Type": "application/json"
}
r = requests.get("https://httpbin.org/headers", headers=headers)
print(r.json())
模拟浏览器请求
import requests
headers = {
"User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 Chrome/120.0 Safari/537.36"
}
r = requests.get("https://www.baidu.com", headers=headers)
r.encoding = "utf-8"
print(r.text)
Cookie 操作
发送 Cookie
import requests
cookies = {"session_id": "abc123", "user": "test"}
r = requests.get("https://httpbin.org/cookies", cookies=cookies)
print(r.json())
获取响应 Cookie
import requests
r = requests.get("https://www.baidu.com")
for key, value in r.cookies.items():
print(f"{key} = {value}")