mirror of
https://github.com/wahyd4/by-agent-for-agent.git
synced 2026-08-08 21:06:00 +10:00
88 lines
3.3 KiB
Python
88 lines
3.3 KiB
Python
# /// script
|
|
# requires-python = ">=3.12"
|
|
# dependencies = [
|
|
# "httpx",
|
|
# ]
|
|
# ///
|
|
import httpx
|
|
import os
|
|
import sys
|
|
import re
|
|
|
|
def download_twitter_media(url, output_dir="downloads"):
|
|
if not os.path.exists(output_dir):
|
|
os.makedirs(output_dir)
|
|
|
|
# 提取推文 ID
|
|
match = re.search(r'status/(\d+)', url)
|
|
if not match:
|
|
print("❌ 无法提取推文 ID")
|
|
return
|
|
tweet_id = match.group(1)
|
|
|
|
print(f"🚀 正在分析推文 {tweet_id}...")
|
|
|
|
headers = {
|
|
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36",
|
|
"Referer": "https://twitter.com/",
|
|
}
|
|
|
|
try:
|
|
# 使用 Syndication API,这是推特用于渲染嵌入卡片的接口,不需要登录
|
|
syndication_url = f"https://cdn.syndication.twimg.com/tweet-result?id={tweet_id}&lang=en"
|
|
|
|
with httpx.Client(headers=headers, timeout=20.0) as client:
|
|
response = client.get(syndication_url)
|
|
if response.status_code != 200:
|
|
print(f"❌ 接口请求失败 ({response.status_code}),推文可能不可见。")
|
|
return
|
|
|
|
data = response.json()
|
|
media_list = data.get("mediaDetails", [])
|
|
|
|
if not media_list:
|
|
print("❌ 未在推文中发现多媒体资源。")
|
|
return
|
|
|
|
print(f"📸 发现 {len(media_list)} 个媒体资源,准备下载...")
|
|
|
|
for i, media in enumerate(media_list):
|
|
media_url = ""
|
|
# 如果是视频/GIF
|
|
if media.get("type") == "video" or media.get("type") == "animated_gif":
|
|
variants = media.get("video_info", {}).get("variants", [])
|
|
# 找比特率最高(画质最好)的 mp4
|
|
mp4_variants = [v for v in variants if v.get("content_type") == "video/mp4"]
|
|
if mp4_variants:
|
|
best_variant = max(mp4_variants, key=lambda v: v.get("bitrate", 0))
|
|
media_url = best_variant.get("url")
|
|
# 如果是图片
|
|
else:
|
|
media_url = media.get("media_url_https")
|
|
if media_url:
|
|
media_url += "?name=orig" # 获取最高原图画质
|
|
|
|
if media_url:
|
|
ext = "mp4" if "video" in media.get("type", "") else "jpg"
|
|
if "format=" in media_url:
|
|
ext_match = re.search(r'format=([a-z]+)', media_url)
|
|
if ext_match: ext = ext_match.group(1)
|
|
|
|
save_path = os.path.join(output_dir, f"twitter_{tweet_id}_{i}.{ext}")
|
|
print(f"📥 正在下载: {media_url}")
|
|
|
|
img_res = client.get(media_url)
|
|
if img_res.status_code == 200:
|
|
with open(save_path, "wb") as f:
|
|
f.write(img_res.content)
|
|
print(f"✅ 保存成功: {save_path}")
|
|
|
|
except Exception as e:
|
|
print(f"💥 运行异常: {e}")
|
|
|
|
if __name__ == "__main__":
|
|
if len(sys.argv) < 2:
|
|
print("用法: uv run scripts/twitter_pro_dl.py <twitter_url>")
|
|
else:
|
|
download_twitter_media(sys.argv[1])
|