ins视频批量下载,instagram批量爬取视频信息【爬虫实战课1】

news2024/9/22 8:26:48

简介

Instagram 是目前最热门的社交媒体平台之一,拥有大量优质的视频内容。但是要逐一下载这些视频往往非常耗时。在这篇文章中,我们将介绍如何使用 Python 编写一个脚本,来实现 Instagram 视频的批量下载和信息爬取。
我们使用selenium获取目标用户的 HTML 源代码,并将其保存在本地:



def get_html_source(html_url):
    option = webdriver.EdgeOptions()
    option.add_experimental_option("detach", True)
    # option.add_argument("--headless")  # 添加这一行设置 Edge 浏览器为无头模式  不会显示页面
    # 实例化浏览器驱动对象,并将配置浏览器选项
    driver = webdriver.Edge(options=option)
    # 等待元素出现,再执行操作
    driver.get(html_url)
    time.sleep(3)

    # ===============模拟操作鼠标滑轮====================
    i=1
    while True:
        # 1. 滚动至页面底部
        last_height = driver.execute_script("return document.body.scrollHeight")
        driver.execute_script("window.scrollTo(0, document.body.scrollHeight);")
        time.sleep(4)
        # 2. 检查是否已经滚动到底部
        new_height = driver.execute_script("return document.body.scrollHeight")
        if new_height == last_height:
            break
        logger.info(f"Scrolled to page{i}")
        i += 1
    html_source=driver.page_source
    driver.quit()
    return html_source
total_html_source = get_h

tml_source(f'https://imn/{username}/')
with open(f'./downloads/{username}/html_source.txt', 'w', encoding='utf-8') as file:
    file.write(total_html_source)

然后,我们遍历每个帖子,提取相关信息并下载对应的图片或视频:,注意不同类型的帖子,下载爬取方式不一样


def downloader(logger,downlod_url,file_dir,file_name):
    logger.info(f"====>downloading:{file_name}")
    # 发送 HTTP 请求并下载视频
    response = requests.get(downlod_url, stream=True)
    # 检查请求是否成功
    if response.status_code == 200:
        # 创建文件目录
        if not os.path.exists("downloads"):
            os.makedirs("downloads")
        # 获取文件大小
        total_size = int(response.headers.get('content-length', 0))
        # 保存视频文件
        # 
        file_path = os.path.join(file_dir, file_name)
        with open(file_path, "wb") as f, tqdm(total=total_size, unit='B', unit_scale=True, unit_divisor=1024, ncols=80, desc=file_name) as pbar:
            for chunk in response.iter_content(chunk_size=1024):
                if chunk:
                    f.write(chunk)
                    pbar.update(len(chunk))
        logger.info(f"downloaded and saved as {file_path}")
        return file_path

    else:
        logger.info("Failed to download .")
        return "err"


def image_set_downloader(logger,id,file_dir,file_name_prx):
    logger.info("downloading image set========")
    image_set_url="https://imm"+id
    html_source=get_html_source(image_set_url)
    # # 打开或创建一个文件用于存储 HTML 源代码
    # with open(file_dir+file_name_prx+".txt", 'w', encoding='utf-8') as file:
    #     file.write(html_source)
# 4、解析出每一个帖子的下载url downlod_url
    download_pattern = r'data-proxy="" data-src="([^"]+)"'
    matches = re.findall(download_pattern, html_source)
    
    download_file=[]
    # # 输出匹配到的结果
    for i, match in enumerate(matches, start=1):
        downlod_url = match.replace("amp;", "")
        file_name=file_name_prx+"_"+str(i)+".jpg"
        download_file.append(downloader(logger,downlod_url,file_dir,file_name))

    desc_pattern = r'<div class="desc">([^"]+)follow'
    desc_matches = re.findall(desc_pattern, html_source)
    desc=""
    for match in desc_matches:
       desc=match
       logger.info(f"desc:{match}")

    return desc,download_file


def image_or_video_downloader(logger,id,file_dir,file_name):
    logger.info("downloading image or video========")
    image_set_url="https://im"+id
    html_source=get_html_source(image_set_url)
    # # 打开或创建一个文件用于存储 HTML 源代码
    # with open(file_dir+file_name+".txt", 'w', encoding='utf-8') as file:
    #     file.write(html_source)
# 4、解析出每一个帖子的下载url downlod_url
    download_pattern = r'href="(https://scontent[^"]+)"'
    matches = re.findall(download_pattern, part)
    # # 输出匹配到的结果
    download_file=[]
    for i, match in enumerate(matches, start=1):
        downlod_url = match.replace("amp;", "")
        download_file.append(downloader(logger,downlod_url,file_dir,file_name))
        # 文件名
    desc_pattern = r'<div class="desc">([^"]+)follow'
    desc_matches = re.findall(desc_pattern, html_source)
    desc=""
    for match in desc_matches:
       desc=match
       logger.info(f"desc:{match}")

    return desc,download_file
parts = total_html_source.split('class="item">')
posts_number = len(parts) - 2

logger.info(f"posts number:{posts_number} ")

for post_index, part in enumerate(parts, start=0):
    id = ""
    post_type = ""
    post_time = ""
    if post_index == 0 or post_index == len(parts) - 1:
        continue
    logger.info(f"==================== post {post_index} =====================================")

    # 解析出每个帖子的时间和 ID
    time_pattern = r'class="time">([^"]+)</div>'
    matches = re.findall(time_pattern, part)
    for match in matches:
        post_time = match
        logger.info(f"time:{match}")
    id_pattern = r'<a href="([^"]+)">'
    id_matches = re.findall(id_pattern, part)
    for match in id_matches:
        id = match
        logger.info(f"id:{id}")

    # 根据帖子类型进行下载
    if '#ffffff' in part:
        post_type = "Image Set"
        logger.info("post_type: Image Set")
        image_name_pex = "img" + str(post_index)
        desc, post_contents = image_set_downloader(logger, id, image_dir, image_name_pex)
    elif "video" in part:
        post_type = "Video"
        logger.info("post_type: Video")
        video_name = "video" + str(post_index) + ".mp4"
        desc, post_contents = image_or_video_downloader(logger, id, video_dir, video_name)
    else:
        logger.info("post_type: Image")
        post_type = "Image"
        img_name = "img" + str(post_index) + ".jpg"
        desc, post_contents = image_or_video_downloader(logger, id, image_dir, img_name)

    # 将信息写入 Excel 文件
    exceller.write_row((post_index, post_time, post_type, desc, ', '.join(post_contents)))

最后,我们调用上述定义的函数,实现图片/视频的下载和 Excel 文件的写入。

结果展示

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

在这里插入图片描述

源码

想要获取源码的小伙伴加v:15818739505 ,手把手教你部署使用哦

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/1605784.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

【面试经典 150 | 二分查找】在排序数组中查找元素的第一个和最后一个位置

文章目录 写在前面Tag题目来源题目解读方法一&#xff1a;二分查找方法二&#xff1a;使用库函数 知识回顾二分查找的三种写法与三个问题常用的二分库函数 写在最后 写在前面 本专栏专注于分析与讲解【面试经典150】算法&#xff0c;两到三天更新一篇文章&#xff0c;欢迎催更……

实战1-批量爬取百度图片(上)

任务需求&#xff1a;输入关键字下载100个图片保存到本地&#xff0c;每个关键字单独存放一个文件夹&#xff08;GUI版&#xff09; 任务描述&#xff1a;当输入关键字时会爬取100个与关键词有关的图片到本地每个关键词单独保存到一个文件夹中&#xff0c;比如说我输入黑客下载…

【技术变现之道】如何打造IT行业的超级个体?

前言 在当今的数字化时代&#xff0c;IT行业蓬勃发展&#xff0c;为具备技术专长的个人提供了无限的可能性。想要成为IT行业的超级个体&#xff0c;实现知识与技能的变现吗&#xff1f;以下是一些高效途径&#xff0c;助你一臂之力&#xff01; 1. 独立接单外包 1&#xff09…

C语言—常用字符串函数剖析

字符串函数 cplusplus.com/reference/cstring/ 更多没有总结到的函数大家可以自行查阅 这篇文章只是把最需要知道的函数做一个总结 strlen size_t strlen ( const char * str );字符串已经 ‘\0’ 作为结束标志&#xff0c;strlen函数返回的是在字符串中 ‘\0’ 前面出现的…

Android开发基础:Activity之间的跳转 向下一个Activity传递数据 给上一个Activity返回数据

目录 一&#xff0c;使用Intent在Activity之间跳转 1.显示使用Intent 2.隐式使用Intent 二&#xff0c;携带数据的跳转 1.Bundle 三&#xff0c;返回数据给上一个Activity 1.registerForActivityResult 一&#xff0c;使用Intent在Activity之间跳转 一个Android应用中包…

语言的未来:深度学习在自然语言处理中的革命

语言的未来&#xff1a;深度学习在自然语言处理中的革命 1 引言 自古以来&#xff0c;语言就是人类表达思想、传递信息、进行社会互动的基石。语言的复杂性既体现在其变化多端的语义、句法和语用层面&#xff0c;同时也反映在人类如何理解和产生自然语言的深奥之中。在这一节中…

java项目的构建工具-Maven

黑马程序员JavaWeb开发教程 文章目录 一、概述1、介绍&#xff08;1&#xff09;介绍&#xff08;2&#xff09;Maven的作用&#xff08;3&#xff09;官网&#xff08;4&#xff09;仓库 2、安装 二、IDEA 集成 Maven1、配置Maven环境2、创建Maven项目&#xff08;1&#xff0…

java 红黑树

01.红黑树的定义&#xff1a; 每一个结点有五个属性&#xff1a;

Jmeter测试学习笔记

第一章 jmeter基础知识 一.Jmeter工具中的组件 1.测试计划&#xff1a;Jmeter测试的起点。容器。 2.线程组&#xff1a;代表一定的用户 3.取样器&#xff1a;发送请求的最小单元 4.逻辑控制器&#xff1a;处理请求逻辑 5.前置处理器&#xff1a;请求之前的操作 6.后置处…

docker部署的nginx配置ssl证书https

申请ssl证书&#xff0c;已腾讯的免费证书为例 2.上传证书到linux服务器 2.1 映射ssql目录 首先确保容器命令已映射宿主机目录&#xff0c;不一定是ssl&#xff0c;也可以是其他路径。 2.2 上传文件到指定路径 以我映射的ssl路径为例&#xff0c;我上传到宿主机的 /usr/local…

字母加密(C语言)

一、题目&#xff1b; 为使电文保密&#xff0c;往往按一定规律将其转换成密码&#xff0c;收报人再按约定的规律将其译回原文。例如&#xff0c;可以按以下规律将电文变成密码&#xff1a;将字母A变成字母E&#xff0c;a变成e&#xff0c;即变成其后的第4个字母&#xff0c;W…

【Shell语言】linux中awk命令

linux中awk命令 看这里放声嘶吼谁也不舍得沉默 宽阔也抓不住我下一秒钟的echo ——《暂时失控》苏打绿 awk命令简介 AWK 是一种处理文本文件的语言&#xff0c;是一个强大的文本分析工具。 之所以叫 AWK 是因为其取了三位创始人 Alfred Aho&#xff0c;Peter Weinberger, 和 B…

密码学 | 数字签名 + 数字证书

&#x1f951;原文&#xff1a;数字签名和数字证书的原理解读 - 知乎 &#x1f951;声明&#xff1a;后文图中若未明确指明&#xff0c;默认是 Bob 的公钥或私钥。 Step1&#xff1a;Bob 有两把钥匙&#xff0c;一把是公钥&#xff0c;另一把是私钥。 Step2&#xff1a;Bob 把…

Redis中的BigKey

Redis中的BigKey 文章目录 Redis中的BigKey什么是BigKey&#xff1f;BigKey的危害找到Bigkey删除BigKey优化BigKeyBigKey对持久化的影响对AOF日志的影响对AOF重写和RDB的影响 什么是BigKey&#xff1f; 大 key 并不是指 key 的值很大&#xff0c;而是 key 对应的 value 很大。…

Docker操作容器打包(commit),压缩(save),挂载(load)

文章目录 前言一、容器打包二、将镜像压缩成tar包三、将tar包挂载为镜像结束 前言 将容器打包成镜像时&#xff0c;你正在将应用程序及其所有依赖项、文件和配置文件捆绑到一个可移植的、独立的单元中。这样做可以确保您的应用程序在不同环境中具有一致的运行方式&#xff0c;…

使用自己训练好的模型YOLOv8进行X-AnyLabeling自动标注

目录 1. 下载项目2. 创建环境3. 运行程序3.1 自行下载和添加官方模型3.2 使用自己训练好的模型标注自己的数据集 本机环境&#xff1a;win 10&#xff0c; GPU 1. 下载项目 git clone https://github.com/CVHub520/X-AnyLabeling.git2. 创建环境 仔细查看项目的README文件 …

FastGPT+ChatGLM3本地部署

FastGPTChatGLM本地部署 本地部署硬性要求&#xff1a;显存13g以上 关于环境的安装就不多赘述&#xff0c;conda pip 可以解决大部分问题 ChatGLM本地运行 m3e-basechatglm3-6b 在huggingface上可以下载上述模型&#xff0c;如果没有梯子可以使用huggingface镜像 从git…

Linux shell 脚本基础与部署SpringCloud实战

博主介绍&#xff1a;✌全网粉丝5W&#xff0c;全栈开发工程师&#xff0c;从事多年软件开发&#xff0c;在大厂呆过。持有软件中级、六级等证书。可提供微服务项目搭建与毕业项目实战&#xff0c;博主也曾写过优秀论文&#xff0c;查重率极低&#xff0c;在这方面有丰富的经验…

Java学习笔记零基础入门1

目录 第一章 Java概述 1.1 什么是程序 1.2 Java 技术体系平台 1.3 Java 重要特点 1.4 Java 的开发工具 4.1 工具选择 1.5 Java 运行机制及运行过程 5.1 Java 语言的特点&#xff1a;跨平台性 5.2 Java 核心机制-Java 虚拟机 [JVMjavavirtual machine] 1.6 什么是JDK&…

C++ PTA 天梯赛 L1-003 个位数统计 L1-005 考试座位号 【范围for循环】【. 与 -> 访问成员】

L1-003 个位数统计 最后一个测试点考察的是当N特别大时&#xff0c;如果用整数存会数据溢出&#xff0c;改成字符串可以增大范围 知识点&#xff1a; 1.范围 for 循环&#xff0c;它对于遍历容器&#xff08;比如字符串&#xff09;中的元素非常方便。在这里&#xff0c;N 是…