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

embedded/2024/9/22 23:18:00/

简介

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.ppmy.cn/embedded/9103.html

相关文章

基于SpringBoot的“体质测试数据分析及可视化”的设计与实现(源码+数据库+文档+PPT)

基于SpringBoot的“体质测试数据分析及可视化”的设计与实现&#xff08;源码数据库文档PPT) 开发语言&#xff1a;Java 数据库&#xff1a;MySQL 技术&#xff1a;SpringBoot 工具&#xff1a;IDEA/Ecilpse、Navicat、Maven 系统展示 体质测试数据分析及可视化设计结构图…

【春季发布】LinkSLA智能运维V6.0发布 聚焦架构升级 新增带外管理

LinkSLA智能运维为企业IT部门提供覆盖资源管理、监控告警、IT服务台、日志管理、MOC值守服务等多项功能为一体的运维平台&#xff0c;通过打通各业务单元、贯穿各技术栈&#xff0c;以故障定位和全生命周期管理为核心&#xff0c;持续保障业务连续性。 本次V6.0版本全面升级&a…

【C++ 多态】(一)虚函数重写✍

文章目录 1.虚函数重写的三个例外1.1协变(基类与派生类虚函数返回值类型不同)1.2析构函数的重写(基类与派生类析构函数的名字不同)1.3派生类可以不写 virtual 2.面试题✍ 1.虚函数重写的三个例外 1.1协变(基类与派生类虚函数返回值类型不同) ①&#x1f34e;协变的概念&#…

前台向后台传递参数时,HTML标签<p>、<span>丢失已经报错等问题解决方案

在保存文档时&#xff0c;前台向后台传递参数时&#xff0c;特殊字符&#xff08;、-&#xff09;标签<p>、<span> 丢失的问题,原因是由于系统后台的xss或者其他拦截器针对脚本语言进行过滤导致的,针对这种情况可以通过使用hex编码绕过 1.前端页面对传输的数据进行…

redis常用5大数据类型

1、string&#xff08;字符串&#xff09; String是Redis中最常用的一种数据类型&#xff0c;也是Redis中最简单的一种数据类型。首先&#xff0c;表面上它是字符串&#xff0c;但其实他可以灵活的表示字符串、整数、浮点数3种值。Redis会自动的识别这3种值。 2、list(列表) …

websocket 连接,http 协议下用 ws, https 协议下必须要使用 wss

解决方案&#xff1a; https 相当于使用 httpssl 认证&#xff0c;使用 https 时 websocket 访问&#xff08;比如建立链接时&#xff09;必须要使用 wss。 详细解释&#xff1a; WebSocket 协议有两个主要版本&#xff1a;“ws”和“wss”。"ws"表示非加密的 Web…

react经验12:等待状态更新

应用场景: 等待react组件内的state发生变更后进行后续操作。 已知问题 通常state的变化会引起dom的刷新&#xff0c;更新state一般使用setState&#xff0c;但这是个异步操作。 如果此时需要立即操作dom&#xff0c;得到的目标dom是刷新之前的样子。 应对方法 方法1:使用u…

登录的几种方式

一、session 1、客户端发送请求&#xff0c;服务器将登录信息存储在 Session 中&#xff0c;Session 依赖于 Cookie&#xff08;cookie指的就是在浏览器里面存储的一种数据&#xff0c;仅仅是浏览器实现的一种数据存储功能。Cookie实际上是一小段的文本信息。&#xff09;&…