Requests 导入模组
import requests as req
Requests 获取网站状态码
# 设定网址
url = "https://www.xyblog.top/"
# 获取网站
r = req.get(url)
# 获取网站状态码
pr int(r) # 输出 <Response [200]>
Requests 获取网站html
# 设定网址
url = "https://www.xyblog.top/"
# 获取网站
r = req.get(url)
# 获取网站状态码
pr int(r.text)
Requests 获取网站headers
# 设定网址
url = "https://www.xyblog.top/"
# 获取网站
r = req.get(url)
# 获取网站 headers
pr int(r.headers)
Requests 获取网络图片
# 设定网址
url = "https://vip.xyblog.cc/wp-content/uploads/2021/08/0c1120a66712-667x375.png"
# 获取网站
r = req.get(url)
# 获取图片
pr int(r.content)
Requests 下载网络图片
# 设定网址
url = "https://vip.xyblog.cc/wp-content/uploads/2021/08/0c1120a66712-667x375.png"
# 获取网站
r = req.get(url)
# 储存图片
with open("image.png", mode="wb") as file:
file.write(r.content)
Requests 传递 GET 参数
# 设定网址
url = "https://www.xyblog.top/"
# 设置参数
params = {
"page": "2",
"count": "5"
}
# 发送请求
r = req.get(url, params=params)
Requests 发送 POST 请求
# 设定网址
url = "http://httpbin.org/post"
# 设置参数
params = {
"page": "2",
"count": "5"
}
# Form形式上传
r = req.post(url, data=params)
# Json形式上传
r = req.post(url, json=params)
Requests 上传文件
# 设定网址
url = "http://httpbin.org/post"
# 打开文件
with open("image.png", "rb") as file:
# 读取文件并设置参数
image = { "upload_image": file.read() }
# 传入参数并且发送请求
r = req.post(url, files=image)
Requests 修改 Headers
# 设定网址
url = "http://httpbin.org/get"
# 设置 User-Agent
headers = {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/92.0.4515.159 Safari/537.36 Edg/92.0.902.84"
}
# 发送请求
r = req.get(url, headers=headers)
Requests 新增 timeout 超时停止
# 设定网址
url = "http://httpbin.org/delay/3"
# 超过600秒 超时
r = req.get(url, timeout=2)
# 报错
版权属于:江筱雨
本文链接:https://www.yuisblog.com/archives/104/
本站未注明转载的文章均为原创,并采用
CC BY-NC-SA 4.0 授权协议,转载请注明来源,谢谢!