【Python爬虫】如何批量获取和下载短视频APP网页端的视频和图集,更新于2024.9.5

本文通过Python-request和Python-selenium实现【批量获取和下载】,【失败重试】两个功能。

一、【批量获取和下载】

通过脚本实现对作者主页所有视频和图集的抓取、下载、列表储存(抓取列表和失败列表)。

输入作者主页网址后,手动下拉到底,确认抓取后,脚本会输出抓取到的视频列表(aid,title,url),停顿后,再通Python-request下载视频或图集,并将下载失败的aid重新储存输出。

# 同时下载视频或图集(更新了用户浏览器,函数整理)
import os
import time
import winsound
from selenium.webdriver.edge.options import Options
from selenium import webdriver
from selenium.webdriver.common.by import By
import re
from requests import utils
import requests
import json
from datetime import datetime
from pprint import pprint


# 采集作者所有作品的ID的函数
def Get_IDs(her_web):
    # 访问网站
    user_data_dir = r"C:\Users\yourCPname\AppData\Local\Microsoft\Edge\User Data"
    options = Options()
    options.add_argument(f"user-data-dir={user_data_dir}")
    wb = webdriver.Edge(options=options)
    # 输入网址
    time.sleep(3)
    wb.get(her_web)
    print('验证')
    input()
    lis = wb.find_elements(By.CSS_SELECTOR, '.niBfRBgX')
    print('共采集到', len(lis), '条作品')
    IDs_Video = []
    IDs_Photo = []
    for li in lis:
        ID = li.find_element(By.CSS_SELECTOR, 'a').get_attribute('href')
        if "note" in ID:
            ID = ID.replace('https://www.douyin.com/note/', '')
            IDs_Photo.append(ID)
        elif "video" in ID:
            ID = ID.replace('https://www.douyin.com/video/', '')
            IDs_Video.append(ID)
        else:
            print('出现未定义格式!')

    print(len(IDs_Video), '条视频', '\n   ', IDs_Video)
    # URLs_Video.reverse()
    print(len(IDs_Photo), '条图集', '\n   ', IDs_Photo)

    return IDs_Video, IDs_Photo


# 通过ID获取响应的函数
def request_header(Uid, ID):
    # 请求url
    url = 'https://www.douyin.com/user/' + Uid + '?modal_id=' + ID
    print(url)
    # 加上一个请求头,伪装成浏览器
    headers = {
        # cookie:用户信息,登录或不登录都有
        'cookie': 'your cookie',
        # user-agent:浏览器信息,版本,电脑
        'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/126.0.0.0 Safari/537.36 Edg/126.0.0.0'

    }
    response = requests.get(url, headers=headers)
    # print(response.text)
    return response, headers


# 获取文件名
def get_title(ID, json_data, file_path, typee):
    try:
        title = json_data['app']['videoDetail']['desc']
    except:
        title = ''
    title = title.replace(' - 抖音', '')
    title = replace_x(title)
    print(title)
    if not title == '':
        title = '-' + title

    if typee == 1:
        title = title[0:100]
        video_name = file_path + ID + title + '.mp4'
        return video_name
    else:
        photofile_name = file_path + ID + title
        return photofile_name

# 下载图集函数
def Download_photo(ID_Video, json
  • 5
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值