Python中如何优化Instagram爬虫的内存使用?
http://ppt.geekbang.org/slide/show/1108
感觉学到了很多用不到的技能... :)
Python中如何优化Instagram爬虫的内存使用?
11 回复
核心是使用流式处理和分页,避免一次性加载所有数据到内存。
import requests
import json
from typing import Iterator
def fetch_instagram_posts(api_url: str, max_posts: int = 1000) -> Iterator[dict]:
"""流式获取Instagram帖子"""
next_cursor = None
post_count = 0
while post_count < max_posts:
# 构建请求参数
params = {'limit': 50}
if next_cursor:
params['cursor'] = next_cursor
# 发送请求
response = requests.get(api_url, params=params)
response.raise_for_status()
data = response.json()
# 逐条处理帖子
for post in data.get('data', []):
if post_count >= max_posts:
return
yield post # 使用生成器逐个返回
post_count += 1
# 获取下一页游标
next_cursor = data.get('paging', {}).get('cursors', {}).get('after')
if not next_cursor:
break
def process_post(post: dict):
"""处理单个帖子(示例)"""
# 这里只处理必要字段,避免存储冗余数据
essential_data = {
'id': post.get('id'),
'caption': post.get('caption', '')[:200], # 截断长文本
'timestamp': post.get('timestamp'),
'media_url': post.get('media_url')
}
# 处理逻辑...
return essential_data
# 使用示例
def main():
api_url = "https://graph.instagram.com/me/media"
# 流式处理,内存中只保持一个帖子
for post in fetch_instagram_posts(api_url, max_posts=500):
processed = process_post(post)
# 立即保存到文件或数据库
with open('posts.jsonl', 'a') as f:
f.write(json.dumps(processed) + '\n')
# 可选:定期清理引用
del processed
print("数据获取完成")
if __name__ == "__main__":
main()
关键优化点:
- 使用生成器:
yield逐个返回数据,避免列表累积 - 分页请求:每次只获取50条数据
- 选择性存储:只提取必要字段,截断长文本
- 立即持久化:处理完立即保存,不留在内存
- 游标分页:使用API的分页机制
如果需要处理媒体文件,使用Response.iter_content()流式下载:
def download_media(url: str, filename: str):
with requests.get(url, stream=True) as r:
with open(filename, 'wb') as f:
for chunk in r.iter_content(chunk_size=8192):
f.write(chunk)
总结:用生成器替代列表,分页请求,及时清理。
最恶心的就是这种网站,你用社交账号授权登录后,再提示你实名验证手机号。社交账户不是都实名过了吗
同不喜欢这种网站
明确表示我点开了又关掉了
看来没必要注册了。。。还是继续看<high performance python>吧
楼上同学,我没有 block 你,你 我,我没有反应吖
点开又关掉了,需要注册这种坑实在是不想踩
不如直接看这个 https://engineering.instagram.com/dismissing-python-garbage-collection-at-instagram-4dca40b29172
想看中文版的,去 infoq
http://www.infoq.com/cn/articles/instagram-pycon-2017
妈了个球的,你是故意不让我们看的么
官方需要登录我也没办法…


