這篇文章主要講解了基于線程池提升request模塊效率的方法,內(nèi)容清晰明了,對(duì)此有興趣的小伙伴可以學(xué)習(xí)一下,相信大家閱讀完之后會(huì)有幫助。
創(chuàng)新互聯(lián)于2013年開始,先為古田等服務(wù)建站,古田等地企業(yè),進(jìn)行企業(yè)商務(wù)咨詢服務(wù)。為古田企業(yè)網(wǎng)站制作PC+手機(jī)+微官網(wǎng)三網(wǎng)同步一站式服務(wù)解決您的所有建站問題。普通方法:爬取梨視頻
import re import time import random import requests from lxml import etree start_time = time.time() url = "https://www.pearvideo.com/category_3" headers = { "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.88 Safari/537.36" } ex = 'srcUrl="(.*?)",vdoUrl=srcUrl' def request_video(url): """ 向視頻鏈接發(fā)送請求 """ return requests.get(url=url, headers=headers).content def save_video(content): """ 將視頻的二進(jìn)制數(shù)據(jù)保存到本地 """ video_name = str(random.randint(100, 999)) + ".mp4" with open(video_name, 'wb') as f: f.write(content) # 獲取首頁源碼 page_text = requests.get(url=url, headers=headers).text tree = etree.HTML(page_text) li_list = tree.xpath('//ul[@class="listvideo-list clearfix"]/li') video_url_list = list() for li in li_list: detail_url = "https://www.pearvideo.com/" + li.xpath('./div/a/@href')[0] # 獲取該視頻頁面的源碼 detail_page_text = requests.get(url=detail_url, headers=headers).text # 正則匹配視頻的URL video_url = re.findall(ex, detail_page_text, re.S)[0] video_url_list.append(video_url) content = request_video(video_url) save_video(content) print("執(zhí)行耗時(shí): ", time.time() - start_time)