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

简介

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=1while 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:breaklogger.info(f"Scrolled to page{i}")i += 1html_source=driver.page_sourcedriver.quit()return html_source
total_html_source = get_html_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_pathelse: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"+idhtml_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_urldownload_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=matchlogger.info(f"desc:{match}")return desc,download_filedef image_or_video_downloader(logger,id,file_dir,file_name):logger.info("downloading image or video========")image_set_url="https://im"+idhtml_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_urldownload_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=matchlogger.info(f"desc:{match}")return desc,download_file
parts = total_html_source.split('class="item">')
posts_number = len(parts) - 2logger.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:continuelogger.info(f"==================== post {post_index} =====================================")# 解析出每个帖子的时间和 IDtime_pattern = r'class="time">([^"]+)</div>'matches = re.findall(time_pattern, part)for match in matches:post_time = matchlogger.info(f"time:{match}")id_pattern = r'<a href="([^"]+)">'id_matches = re.findall(id_pattern, part)for match in id_matches:id = matchlogger.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.mzph.cn/pingmian/186.shtml

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

相关文章

Python路面车道线识别偏离预警

程序示例精选 Python路面车道线识别偏离预警 如需安装运行环境或远程调试&#xff0c;见文章底部个人QQ名片&#xff0c;由专业技术人员远程协助&#xff01; 前言 这篇博客针对《Python路面车道线识别偏离预警》编写代码&#xff0c;代码整洁&#xff0c;规则&#xff0c;易…

AOP动态修改注解值及异步子线程请求头丢失问题

1、动态注入参数&#xff1a;通过AOP注解占位符&#xff0c;匹配目标方法参数&#xff0c;可用于日志记录等场景 AOP 注解动态注入参数 - 简书 2、spel表达式匹配目标方法的参数进行动态入参 自定义注解动态入参绑定_注解参数值动态注入-CSDN博客 3、Java没有提供直接设置线…

Leetcode 225:用队列实现栈

请你仅使用两个队列实现一个后入先出&#xff08;LIFO&#xff09;的栈&#xff0c;并支持普通栈的全部四种操作&#xff08;push、top、pop 和 empty&#xff09;。 实现 MyStack 类&#xff1a; void push(int x) 将元素 x 压入栈顶。int pop() 移除并返回栈顶元素。int to…

tsconfig.json文件常用配置

最近在学ts&#xff0c;因为tsconfig的配置实在太多啦&#xff0c;所以写此文章用作记录&#xff0c;也作分享 作用&#xff1f; tsconfig.jsono是ts编译器的配置文件&#xff0c;ts编译器可以根据它的信息来对代码进行编译 初始化一个tsconfig文件 tsc -init配置参数解释 …

测试 rtpengine 的 sip-source 参数

修改 /etc/rtpengine/rtpengine.conf 文件&#xff0c;增加一行配置&#xff1a; sip-source true # 一般不需要这样配置&#xff0c;本文仅为说明问题 offfer 部分的日志如下&#xff1a; [1713246486.390578] DEBUG: [1-5025192.168.43.126]: [control] Dump for offer from…

HZNUCTF第五届校赛实践赛初赛 Web方向 WriteUp

ezssti 很简单的ssti 源码给了&#xff0c;调用Eval即可执行命令 package mainimport ("fmt""net/http""os/exec""strings""text/template" )type User struct {Id intName stringPasswd string }func (u User) Ev…

Python学习从0开始——项目一day01爬虫

Python学习从0开始——项目一day01爬虫 一、导入代码二、使用的核心库三、功能测试3.1初始代码3.2新建文件3.3代码调试 四、页面元素解析4.1网页4.2修改代码4.3子页面4.4修改代码 一、导入代码 在Inscode新建一个python类型的项目&#xff0c;然后打开终端&#xff0c;粘贴以下…

WINFORM画笔实现画板(如何实现橡皮擦和清空画板功能)

C#内部并没有提供橡皮擦功能所以&#xff0c;只能使用画笔和颜色填充来实现橡皮擦和清空画板功能。 此次小编写了一个简易的画板功能其中包含橡皮擦&#xff0c;清空面板&#xff0c;在窗体运行中修改画笔颜色和像素等功能。 代码如下: using Sunny.UI; using Sunny.UI.Win32…

二叉搜索树(BST)

二叉搜索树是一种特殊的二叉树&#xff0c;它具有以下性质&#xff1a; 任意一个节点的左子树上的所有节点的值都小于该节点的值。任意一个节点的右子树上的所有节点的值都大于该节点的值。任意一个节点的左右子树也都是二叉搜索树。二叉搜索树中不存在重复的值。 二叉搜索树…

《七》布局QLayout类

QLayout简介 QLayout是由具体类 QBoxLayout、QGridLayout、QFormLayout 和 QStackedLayout继承的抽象基类。 对于 QLayout子类或 QMainWindow的用户&#xff0c;很少需要使用 QLayout 提供的基本功能&#xff0c;例如 setSizeConstraint() 或 setMenuBar()。Qt 布局系统提供了…

程序员购车指南

哈喽大家好&#xff0c;我是咸鱼。 爱车可以说是大部分男人的天性&#xff0c;而我对汽车的热情却远不及对手表的钟爱&#xff08;痴迷劳力士&#xff09;。以至于我的朋友掏出车钥匙指着上面的苹果树标志跟我介绍奔驰 AMG 系列的强劲性能和马力时&#xff0c;我只能尽量假装自…

【三维Dvhop定位】基于麻雀搜索算法的多通信半径和跳距加权的三维Dvhop定位算法【Matlab代码#81】

文章目录 【可更换其他算法&#xff0c;获取资源请见文章第6节&#xff1a;资源获取】1. Dvhop定位算法2. 麻雀搜索算法3. 多通信半径和跳距加权策略3.1 多通信半径策略3.2 跳距加权策略 4. 部分代码展示5. 仿真结果展示6. 资源获取 【可更换其他算法&#xff0c;获取资源请见文…

Oracle-TDE数据加密功能

1 Oracle TDE 1.1 TDE介绍 Oracle TDE是数据库层对存储的用户敏感数据进行的静态加密&#xff0c;加密数据满足主流的安全法规&#xff08;如 PCI DSS&#xff09;相关的加密要求&#xff0c;可以防止数据文件被其他非数据库读取方式访问的情况下(如通过工具直接打开读取数据文…

Java程序生成可执行的exe文件 详细图文教程

1.Java编辑器&#xff0c;如&#xff1a;idea、eclipse等&#xff0c;下载地址&#xff1a;IntelliJ IDEA: The Capable & Ergonomic Java IDE by JetBrainshttps://www.jetbrains.com/idea/2.exe4j&#xff0c;下载地址&#xff1a;ej-technologies - Java APM, Java Prof…

ansible-tower连接git实现简单执行playbook

前提&#xff1a;安装好ansible-tower和git&#xff0c;其中git存放ansible得剧本 其中git中得内容为&#xff1a; --- - name: yjxtesthosts: yinremote_user: rootgather_facts: noroles:- testroles/test/tasks/main.yml #文件内容 --- #- name: Perform Test Task # tas…

算法和数据结构简介

文章目录 算法的分类硬计算类算法软计算类算法 数据结构分类(宏观)连续结构跳转结构 链表按值传递&#xff0c;按引用传递单链表和双链表链表反转需求实现代码 合并两个有序链表需求 实现代码 算法的分类 硬计算类算法 精确求解&#xff0c;但是某些问题都是使用硬计算类的算法…

ant-design-vue Table+Form表单实现表格内置表单验证,可自定义验证规则,触发必填项

代码示例如下&#xff1a; <!-- --> <template><a-button type"primary" style"padding-left: 10px; padding-right: 10px" click"handleAddRow"><template #icon><plus-outlined /></template>新增</…

2024年大唐杯官网模拟题

单选(出题角度很奇怪&#xff0c;不用太纠结&#xff09; 5G NR系统中&#xff0c;基于SSB的NR同频测量在measconfig里最多可以配置&#xff08; &#xff09;个SMTC窗口。 A、3 B、4 C、1 D、2 答案&#xff1a;D 2个 只在官网找到了这张PPT 5G 中从BBU到AAU需要保证&#x…

Python分析之3 种空间插值方法

插值是一个非常常见的数学概念,不仅数据科学家使用它,而且各个领域的人们也使用它。然而,在处理地理空间数据时,插值变得更加复杂,因为您需要基于几个通常稀疏的观测值创建代表性网格。 在深入研究地理空间部分之前,让我们简要回顾一下线性插值。 为了演示的目的,我将使…

Spring Security详细学习第一篇

Spring Security 前言Spring Security入门编辑Spring Security底层原理UserDetailsService接口PasswordEncoder接口 认证登录校验密码加密存储退出登录 前言 本文是作者学习三更老师的Spring Security课程所记录的学习心得和笔记知识&#xff0c;希望能帮助到大家 Spring Sec…