目录
基础链接 :?01-python-request库使用01
import requests
# 定义一个通用方法:
def get_text_from_web(url):
headers = {
# 自己通过浏览器查找替换即可
"user-Agent":'Mozilla/5.0 (Wi、****** Safari/537.36'
}
try:
resp = requests.get(url,headers=headers,timeout=10)
resp.raise_for_status()
resp.encoding = resp.apparent_encoding
return resp.text
except Exception as e:
print("产生异常",e)
# 调用函数:
res = get_text_from_web("https://api.xygeng.cn/one")
print(res)
# requests下载图片.py --- 一次读取,一次写出
# 图片地址:
import requests
img_url1 = "https://tppic.chinaz.net/files/default/imgs/2023-10-27/4d3b05335f9a07d4_big.jpg";
img_url2 = "https://tppic.chinaz.net/files/default/imgs/2023-07-24/07d49ae71be62266_big.jpg"
def downLoad_img(url):
fileName = url.split('/')[-1] # 获取文件名字
headers = {
'user-Agent': "Mozill *** Chrome/120.0.0.0 Safari/537.36"
}
try:
resp = requests.get(url, headers=headers)
resp.raise_for_status() # 如果响应不是200 抛异常
with open(fileName, 'wb') as fW:
fW.write(resp.content)
except Exception as e:
print('抛出异常:', e)
finally:
print("下载完毕:",fileName)
# 下载两张图片:
downLoad_img(img_url1)
downLoad_img(img_url2)
print("执行完毕")
get请求携带数据使用params参数配置:
# 06-requests带参数.py --- 发送get请求
import requests
url = ""
headers={}
params = {} #使用params传递参数
requests.get(url,headers= "",params=params)
post请求携带数据使用data参数配置:
# 06-requests带参数.py --- 发送post请求
import requests
url = ""
headers = {}
data = {} # 使用data参数传递字典
requests.post(url, headers="", data=data)
# time: 2024/1/12 15:01
# author: keep_di
# 07-requests下载视频.py
# 视频地址: 使用图片测试, 注意修改User-Agent 再运行!
import requests
urlVideo = 'https://tppic.chinaz.net/files/default/imgs/2023-07-24/07d49ae71be62266_big.jpg'
def downVideo(url, ):
headers = {
"User-Agent": 'Mozilla/ **** Safari/537.36'}
fileName = url.split('/')[-1]
try:
respVideo = requests.get(url, headers=headers, stream=True)
respVideo.raise_for_status()
contentLength = int(respVideo.headers['content-length'])
print(f'视频的字节为{contentLength}')
buffer_size = 1024 * 8 # 缓存大小,每次读取的字节数
size_downloaded = 0
with open(fileName, 'wb') as fp:
for data in respVideo.iter_content(buffer_size):
fp.write(data) # 向文件中写入数据
size_downloaded += len(data) # 统计已下载数据大小
# 格式化显示小数点后两位
print(f'当前的下载进度:{size_downloaded / contentLength * 100:.2f}%')
print("下载完成 :" + fileName)
except Exception as e:
print("抛出异常:", e)
downVideo(urlVideo)
requests模块中的session类能够自动处理发送请求获取响应过程中产生的cookie,进而达到状态保持目的。
# 08-requests的登录保持.py
import requests
session = requests.session() # 获取session对象
# 先使用session请求一次,这样cookie就自动保存在了session中!
session.get("url",headers={},...)
# 再请求,就不需要携带cookie参数了!
resp = session.get('url',data={},...)