Python爬取网站视频资源

思路:

在界面找到视频对应的html元素位置,观察发现视频的url为https://www.pearvideo.com/video_+视频的id,而这个id在html中的href中,所以第一步需要通过xpath捕获到所需要的id

https://www.pearvideo.com/video_+id的页面,通过控制台查看返回的响应消息,发现没有视频数据,说明视频是进入页面后由其他请求发起获得

在搜索框中搜索mp4,发现视频文件对应的请求,观察请求的url与负载,发现负载1为视频的id另一个为随机生成的数字。方法为get

由其返回的视频url与元素中的url进行对比发现是用cont-id替换了一段数字。这一段的url就为视频的url

代码实现:

代码:

python 复制代码
import os
from lxml import etree
import requests
import time
from fake_useragent import UserAgent
# UA绕过
ua = UserAgent()
headers = {
    'User-Agent': ua.random
}

def deal_video(id):
    time.sleep(1)
    url = "https://www.pearvideo.com/video_" + id
    url1 = "https://www.pearvideo.com/videoStatus.jsp?contId=" + id
    new_headers = headers
    new_headers["Referer"] = url
    page_json = requests.get(url=url1, headers=new_headers).json()
    video_src = page_json["videoInfo"]["videos"]["srcUrl"]
    key = "cont-"+url1.split("=")[1]
    return video_src.replace(video_src.split('/')[6].split('-')[0], key)

def save_video(video_src,name):
    time.sleep(1)
    print("正在下载"+name)
    videoData = requests.get(url=video_src, headers=headers).content
    if not os.path.exists("./videoLibs"):
        os.mkdir("./videoLibs")
    with open("./videoLibs/"+name+".mp4",'wb') as fp:
        fp.write(videoData)
        print(dic['name']+" 下载完成")


post_url = 'https://www.pearvideo.com/category_1'
# 发出请求
page_text = requests.get(url=post_url, headers=headers).text
# 数据处理
urls = []
tree = etree.HTML(page_text)
videos = tree.xpath('//a[@class="vervideo-lilink actplay"]')
for video in videos:
    time.sleep(0.5)
    name = video.xpath('./@href')[0]
    information_url = "https://www.pearvideo.com/" + name
    h = headers
    id = name.split("_")[1]
    #从函数中获取到视频的资源位置
    video_url=deal_video(id)
    dic = {
        'name': name,
        'url': video_url
    }
    save_video(video_url,name)
    urls.append(dic)

解析:

获取主页的text,然后通过xpath找到所以的视频<a>标签,for循环标签,获得href中的id。存储url与名字。通过视频id进入deal_video函数

在url后动态添加视频id,一个作为访问源url,表示从这个页面向url1发起请求,请求头需要携带Referer。通过字典查找获得srcUrl中的视频链接,并将其数字部分替换为cont-id(KEY)。返回视频的url。

获取视频链接后进入保存函数。

向视频链接发起请求保存到文件夹中

相关推荐
bst@微胖子39 分钟前
Python高级语法之selenium
开发语言·python·selenium
王小义笔记44 分钟前
Postman如何流畅使用DeepSeek
开发语言·测试工具·lua·postman·deepseek
查理零世2 小时前
【蓝桥杯集训·每日一题2025】 AcWing 6118. 蛋糕游戏 python
python·算法·蓝桥杯
魔尔助理顾问3 小时前
一个简洁高效的Flask用户管理示例
后端·python·flask
java1234_小锋3 小时前
一周学会Flask3 Python Web开发-request请求对象与url传参
开发语言·python·flask·flask3
流星白龙5 小时前
【C++】36.C++IO流
开发语言·c++
诚信爱国敬业友善6 小时前
常见排序方法的总结归类
开发语言·python·算法
nbsaas-boot7 小时前
Go 自动升级依赖版本
开发语言·后端·golang
架构默片7 小时前
【JAVA工程师从0开始学AI】,第五步:Python类的“七十二变“——当Java的铠甲遇见Python的液态金属
java·开发语言·python
不只会拍照的程序猿8 小时前
从插入排序到希尔排序
java·开发语言·数据结构·算法·排序算法