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。

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

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

相关推荐
LyaJpunov13 分钟前
C++中move和forword的区别
开发语言·c++
程序猿练习生18 分钟前
C++速通LeetCode中等第9题-合并区间
开发语言·c++·leetcode
一名路过的小码农28 分钟前
C/C++动态库函数导出 windows
c语言·开发语言·c++
m0_6312704030 分钟前
标准c语言(一)
c语言·开发语言·算法
万河归海42830 分钟前
C语言——二分法搜索数组中特定元素并返回下标
c语言·开发语言·数据结构·经验分享·笔记·算法·visualstudio
Messiah___36 分钟前
【论文阅读】Slim Fly: A Cost Effective Low-Diameter Network Topology 一种经济高效的小直径网络拓扑
开发语言·php
农民小飞侠1 小时前
python AutoGen接入开源模型xLAM-7b-fc-r,测试function calling的功能
开发语言·python
指尖流烟1 小时前
C#调用图表的使用方法
开发语言·c#
战神刘玉栋1 小时前
《程序猿之设计模式实战 · 观察者模式》
python·观察者模式·设计模式
敲代码不忘补水1 小时前
Python 项目实践:简单的计算器
开发语言·python·json·项目实践