用于测试图床的网络状况,同时定期访问所有图片以优化CDN缓存
1.获取指定相册所有图片URL
import requests
# 授权令牌,输入获取到的图床token
token = "Bearer gcPBOco"
# 特定相册ID
album_id = 2 # 替换成实际的相册ID
def get_all_image_urls(token, album_id):
# 获取特定相册的所有图片链接,注意修改为图床域名
base_url = "https://xx.xx/api/v1/images"
headers = {
"Authorization": token,
"Accept": "application/json"
}
all_image_urls = []
# 获取第一页数据
page = 1
while True:
params = {
"album_id": album_id,
"page": page
}
response = requests.get(base_url, headers=headers, params=params)
result = response.json()
if result["status"] and "data" in result["data"]:
image_urls = [image["links"]["url"] for image in result["data"]["data"]]
all_image_urls.extend(image_urls)
# 如果当前页是最后一页,则退出循环
if result["data"]["current_page"] == result["data"]["last_page"]:
break
# 否则,继续下一页
page += 1
else:
break
return all_image_urls
# 获取相册内所有图片的链接地址
all_image_urls = get_all_image_urls(token, album_id)
#if all_image_urls:
# for image_url in all_image_urls:
# print(image_url)
#else:
# print("null")
# 将结果保存到文件
output_file_path = f"image_urls_{album_id}.txt" # 加上相册ID的文件名
with open(output_file_path, "w") as file:
if all_image_urls:
for image_url in all_image_urls:
file.write(image_url + "\n")
else:
file.write("null")
print(f"Image URLs saved to {output_file_path}")
2.调用相册URL程序以访问所有图片
import subprocess
import requests
import time
import glob
# 调用url.py生成文件
subprocess.run(["python3", "url.py"])
# 动态获取文件路径
file_path_pattern = "image_urls_*.txt"
file_paths = glob.glob(file_path_pattern)
if not file_paths:
print(f"No files matching the pattern '{file_path_pattern}' found.")
else:
for file_path in file_paths:
# 通过文件名获取相册ID
album_id = file_path.split("_")[-1].split(".")[0]
# 读取文件中的图片链接
with open(file_path, "r") as file:
image_urls = [line.strip() for line in file]
# 访问图片链接并显示进度
for index, image_url in enumerate(image_urls, start=1):
start_time= time.time()
try:
response = requests.get(image_url)
response.raise_for_status() # 检查是否请求成功
# 如果需要保存图片或其他处理,请在这里添加对应的代码
end_time = time.time()
elapsed_time =end_time - start_time
print(f"Visited {index}/{len(image_urls)} URLs in Album ID {album_id}. "
f"Status Code: {response.status_code}, Time Elapsed: {elapsed_time:.2f} seconds. "
f"URL: {image_url}")
except requests.exceptions.RequestException as e:
print(f"Error visiting URL {index}/{len(image_urls)} in Album ID {album_id}: {e}")
# 等待3秒再访问下一个链接
if index < len(image_urls):
time.sleep(3)
Comments NOTHING