(编辑:jimmy 日期: 2024/11/14 浏览:2)
本实例主要进行线程池创建,多线程获取、存储视频文件
梨视频:利用线程池进行视频爬取
#爬取梨视频数据 import requests import re from lxml import etree from multiprocessing.dummy import Pool import random # 定义获取视频数据方法 def getVideoData(url): # url为列表中的视频url return requests.get(url=url,headers=headers).content # 定义存储数据方法 def saveVideo(data): fileName = str(random.randint(0,5000))+'.mp4' with open(fileName,'wb') as fp: fp.write(data) # 爬取数据 #实例化一个线程池对象,开启5个线程池 pool = Pool(5) url = 'https://www.pearvideo.com/category_1' headers = { 'User-Agent':'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.119 Safari/537.36' } page_text = requests.get(url=url,headers=headers).text tree = etree.HTML(page_text) li_list = tree.xpath('//div[@id="listvideoList"]/ul/li') video_url_list = [] # 存的是将要下载视频的url for li in li_list: detail_url = 'https://www.pearvideo.com/'+li.xpath('./div/a/@href')[0] detail_page = requests.get(url=detail_url,headers=headers).text #因为视频连接不在标签汇中,而是一个js语句,所以用正则匹配 video_url = re.findall('srcUrl="(.*",vdoUrl',detail_page,re.S)[0] video_url_list.append(video_url) # map函数的应用:参数1:回调函数,参数2:列表; #将列表中的参数赋值给回调函数的形参,让回调函数处理 video_data_list = pool.map(getVideoData,video_url_list) pool.map(saveVideo,video_data_list)
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。