Python中如何实现批量下载Instagram图片或视频的小程序?

大致的需要是这样:能批量下载 ins,指定账户的,所有图片。包括一条 ins 下有多张图的也需要全部下完。

我之前买的是一个公众号的 vip 服务,现在倒闭了。操作是只要发需要的 ins 账户地址,服务器自动打包一个下载连接。整体体验不错,但是目前倒闭了。

目前是用国外的插件( Downloader for Instagram 和 InstaG Downloader )。对于数量不多的情况比较理想,但是如果指定账户发的图太多就会卡住。一般读图阶段都很顺畅(感觉像是在解析下载地址和下载),但是最后生产打包连接的时候,就卡住了。暂时不知道原因。

感觉技术要求不会很麻烦。如果正好你有空,能帮忙小弟就好了。

在线等哦~


Python中如何实现批量下载Instagram图片或视频的小程序?

2 回复
import instaloader
import os
from concurrent.futures import ThreadPoolExecutor
import logging

class InstagramDownloader:
    def __init__(self, download_dir="instagram_downloads"):
        self.loader = instaloader.Instaloader(
            dirname_pattern=download_dir,
            save_metadata=False,
            download_videos=True,
            download_video_thumbnails=False,
            download_geotags=False,
            download_comments=False,
            compress_json=False
        )
        self.download_dir = download_dir
        os.makedirs(download_dir, exist_ok=True)
        logging.basicConfig(level=logging.INFO)
        
    def download_single_post(self, shortcode):
        """下载单个帖子"""
        try:
            post = instaloader.Post.from_shortcode(self.loader.context, shortcode)
            self.loader.download_post(post, target=post.owner_username)
            logging.info(f"下载完成: {shortcode}")
            return True
        except Exception as e:
            logging.error(f"下载失败 {shortcode}: {str(e)}")
            return False
    
    def download_profile_posts(self, username, count=10):
        """下载用户的最新帖子"""
        try:
            profile = instaloader.Profile.from_username(self.loader.context, username)
            posts = list(profile.get_posts())[:count]
            
            with ThreadPoolExecutor(max_workers=3) as executor:
                results = list(executor.map(
                    lambda p: self.loader.download_post(p, target=username),
                    posts
                ))
            
            logging.info(f"已下载 {username} 的 {len(posts)} 个帖子")
            return True
        except Exception as e:
            logging.error(f"下载用户 {username} 失败: {str(e)}")
            return False
    
    def download_from_urls(self, urls_file="urls.txt"):
        """从文件读取URL批量下载"""
        if not os.path.exists(urls_file):
            logging.error(f"文件不存在: {urls_file}")
            return
        
        with open(urls_file, 'r') as f:
            urls = [line.strip() for line in f if line.strip()]
        
        shortcodes = []
        for url in urls:
            if "/p/" in url:
                shortcode = url.split("/p/")[1].split("/")[0]
                shortcodes.append(shortcode)
        
        with ThreadPoolExecutor(max_workers=3) as executor:
            executor.map(self.download_single_post, shortcodes)

# 使用示例
if __name__ == "__main__":
    downloader = InstagramDownloader()
    
    # 方式1: 下载单个帖子
    # downloader.download_single_post("CxampleShortcode123")
    
    # 方式2: 下载用户最新10个帖子
    # downloader.download_profile_posts("target_username", count=10)
    
    # 方式3: 从urls.txt批量下载
    # urls.txt每行一个帖子URL
    # downloader.download_from_urls("urls.txt")

核心要点:

  1. 使用instaloader库,先安装:pip install instaloader
  2. 三种下载方式:单帖子、用户最新帖子、批量URL下载
  3. 线程池加速批量下载,避免频繁请求被封
  4. 自动按用户名创建文件夹整理文件

注意点:

  • 需要遵守Instagram使用条款
  • 频繁访问可能触发限制,可调整max_workers和添加延时
  • 私密账号无法直接下载

一句话建议: 用instaloader库配合线程池,注意控制请求频率。


请不要重复发帖

回到顶部