1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89
| import requests from lxml import etree import random import re from multiprocessing.dummy import Pool import time import aiohttp import asyncio import aiofiles
url = "https://www.pearvideo.com/popular" headers = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/123.0.0.0 Safari/537.36"}
resp = requests.get(url=url, headers=headers) tree = etree.HTML(resp.text)
contIds, names = tree.xpath('//ul[@class="popular-list"]//div[@class="popularem-ath"]/a/@href'), tree.xpath('//ul[@class="popular-list"]//div[@class="popularem-ath"]/a/h2/text()') contIds, names = [x.split("_")[1] for x in contIds], [x + ".mp4" for x in names]
start_time = time.time()
url = []
for i in range(3): contId, name = contIds[i], names[i] ajax_url = "https://www.pearvideo.com/videoStatus.jsp?" param = {"contId": contId, "mrd":str(random.random())} headers["Referer"] = "https://www.pearvideo.com/video_" + contId resp = requests.get(url=ajax_url, params=param,headers=headers)
video_url = resp.json()["videoInfo"]["videos"]["srcUrl"] video_url = re.sub(r"/\d{10,}", f"/cont-{contId}", video_url) url.append({"url":video_url, "name":name})
def main_pool(): def get_video(url): name = url["name"] print("正在下载" + name + "...") video_resp = requests.get(url=url["url"], headers=headers) with open(name, "wb") as f: f.write(video_resp.content) print("成功下载" + name)
pool = Pool(4) pool.map(get_video, url)
def main_async(): async def get_video(url): name = url["name"] print("正在下载" + name + "...") async with aiohttp.ClientSession() as session: async with await session.get(url=url["url"], headers=headers) as video_resp: content = await video_resp.read() async with aiofiles.open(name, "wb") as f: await f.write(content) print("成功下载" + name)
loop = asyncio.get_event_loop() tasks = [asyncio.ensure_future(get_video(url)) for url in url] loop.run_until_complete(asyncio.wait(tasks))
main_async()
end_time = time.time() print(f"耗时{end_time - start_time}s")
|