进阶用法
Python API 进阶
使用 instaloader Python API 进行高级操作
🐍 Python API 进阶
Instaloader 实例配置
import instaloader
L = instaloader.Instaloader(
# 下载选项
download_pictures=True, # 下载图片
download_videos=True, # 下载视频
download_video_thumbnails=False, # 不下载视频缩略图
download_geotags=False, # 不下载地理信息
download_comments=False, # 不下载评论
save_metadata=True, # 保存元数据
compress_json=False, # JSON 不压缩
# 文件名模式
filename_pattern="{date_utc:%Y%m%d}_{shortcode}",
dirname_pattern="{profile}",
# 速率控制
max_connection_attempts=3,
request_timeout=300.0,
# 其他
quiet=False, # 显示进度
user_agent=None, # 自定义 UA
)自定义下载逻辑
import instaloader
from datetime import datetime
from itertools import islice
L = instaloader.Instaloader()
L.load_session_from_file("YOUR_USERNAME")
profile = instaloader.Profile.from_username(L.context, "target_user")
# 只下载轮播帖(多图)
for post in profile.get_posts():
if post.typename == "GraphSidecar": # 轮播帖
L.download_post(post, target="carousels")
# 只下载特定时间段内点赞数 > 500 的视频
since = datetime(2024, 6, 1)
for post in profile.get_posts():
if post.date_utc < since:
break
if post.is_video and post.likes > 500:
L.download_post(post, target="popular_videos")处理轮播帖(Sidecar)
import instaloader
L = instaloader.Instaloader()
post = instaloader.Post.from_shortcode(L.context, "CxxxxxxYYYY")
if post.typename == "GraphSidecar":
for index, node in enumerate(post.get_sidecar_nodes()):
print(f"图片 {index + 1}: {node.display_url}")
print(f" 是视频: {node.is_video}")
if node.is_video:
print(f" 视频 URL: {node.video_url}")下载个人资料图片
import instaloader
L = instaloader.Instaloader()
profile = instaloader.Profile.from_username(L.context, "profile_name")
# 下载头像
L.download_profilepic(profile)构建数据分析管道
import instaloader
import json
from itertools import islice
L = instaloader.Instaloader()
L.load_session_from_file("YOUR_USERNAME")
profile = instaloader.Profile.from_username(L.context, "target_user")
# 收集帖子数据用于分析
posts_data = []
for post in islice(profile.get_posts(), 100):
posts_data.append({
"shortcode": post.shortcode,
"date": post.date_utc.isoformat(),
"likes": post.likes,
"comments": post.comments,
"is_video": post.is_video,
"caption": post.caption,
"hashtags": post.caption_hashtags,
"typename": post.typename, # GraphImage, GraphVideo, GraphSidecar
})
# 导出为 JSON
with open("posts_analysis.json", "w", encoding="utf-8") as f:
json.dump(posts_data, f, ensure_ascii=False, indent=2)
print(f"已收集 {len(posts_data)} 个帖子的数据")instaloader 的 Python API 是面向对象设计的,Profile、Post、StoryItem 等类提供了丰富的属性和方法。