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=1
    while True:
        # 1. 滚动至页面底部
        last_height = driver.execute_script("return document.body.scrollHeighriver.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 文件的写入。

结果展示

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

在这里插入图片描述

源码

想要获取源码的小伙伴加我哦 ,手把手教你部署使用哦
在这里插入图片描述

  • 4
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
如果您下载了本程序,但是该程序无法运行,或者您不会部署,那么您可以选择退款或者寻求我们的帮助(如果找我们帮助的话,是需要追加额外费用的) 爬虫(Web Crawler)是一种自动化程序,用于从互联网上收集信息。其主要功能是访问网页、提取数据并存储,以便后续分析或展示。爬虫通常由搜索引擎、数据挖掘工具、监测系统等应用于网络数据抓取的场景。 爬虫的工作流程包括以下几个关键步骤: URL收集: 爬虫从一个或多个初始URL开始,递归或迭代地发现新的URL,构建一个URL队列。这些URL可以通过链接分析、站点地图、搜索引擎等方式获取。 请求网页: 爬虫使用HTTP或其他协议向目标URL发起请求,获取网页的HTML内容。这通常通过HTTP请求库实现,如Python中的Requests库。 解析内容: 爬虫对获取的HTML进行解析,提取有用的信息。常用的解析工具有正则表达式、XPath、Beautiful Soup等。这些工具帮助爬虫定位和提取目标数据,如文本、图片、链接等。 数据存储: 爬虫将提取的数据存储到数据库、文件或其他存储介质中,以备后续分析或展示。常用的存储形式包括关系型数据库、NoSQL数据库、JSON文件等。 遵守规则: 为避免对网站造成过大负担或触发反爬虫机制,爬虫需要遵守网站的robots.txt协议,限制访问频率和深度,并模拟人类访问行为,如设置User-Agent。 反爬虫应对: 由于爬虫的存在,一些网站采取了反爬虫措施,如验证码、IP封锁等。爬虫工程师需要设计相应的策略来应对这些挑战。 爬虫在各个领域都有广泛的应用,包括搜索引擎索引、数据挖掘、价格监测、新闻聚合等。然而,使用爬虫需要遵守法律和伦理规范,尊重网站的使用政策,并确保对被访问网站的服务器负责。
Instagram爬虫是一种通过程序自动化获取Instagram上的数据的方法。以下是一个简单的Instagram爬虫的实现方法: 1.首先,需要安装Python和Selenium库。 2.使用Selenium库打开一个浏览器窗口,并访问Instagram网站。 3.输入用户名和密码,登录Instagram账户。 4.使用Selenium库模拟用户在Instagram上的操作,例如搜索用户、获取用户信息、获取用户发布的图片和视频等。 5.使用BeautifulSoup库解析网页内容,提取所需的数据。 6.将数据保存到本地文件或数据库中。 以下是一个简单的Instagram爬虫的代码示例: ```python from selenium import webdriver from bs4 import BeautifulSoup # 打开浏览器窗口 driver = webdriver.Chrome() driver.get("https://www.instagram.com/") # 登录Instagram账户 username = driver.find_element_by_name("username") password = driver.find_element_by_name("password") username.send_keys("your_username") password.send_keys("your_password") login_button = driver.find_element_by_xpath("//button[@type='submit']") login_button.click() # 搜索用户 search_box = driver.find_element_by_xpath("//input[@placeholder='Search']") search_box.send_keys("user_name") search_box.submit() # 获取用户信息 user_info = driver.find_element_by_xpath("//div[@class='v1Nh3 kIKUG _bz0w']") user_info.click() html = driver.page_source soup = BeautifulSoup(html, 'html.parser') user_name = soup.find('h2', {'class': 'BrX75'}).text user_description = soup.find('div', {'class': '-vDIg'}).text # 获取用户发布的图片和视频 images = soup.find_all('div', {'class': 'v1Nh3 kIKUG _bz0w'}) for image in images: image_url = image.find('a')['href'] # 下载图片或视频 # 关闭浏览器窗口 driver.quit() ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值