高性能异步编程
目的:在爬虫中使用异步实现高性能的数据爬取操作
异步编程的方式:
- 多线程,多进程(不建议使用,因为爬虫的数量有限制):
好处:可以为相关阻塞的操作单独开启进程或线程,阻塞操作就可以异步执行。
弊端:无法无限制的开启多线程或者多进程。
(开启多线程或者多进程会影响cpu的效率,进而影响爬取数据的效率)
- 线程池、进程池(适当的使用):
好处:我们可以降低系统对进程或者线程创建或者销毁的一个频率,从而很好地降低系统的开销。
(不需要对进程或者线程进行频繁的创建或者销毁)
弊端:池中线程或者进程的数量是有上限的。
import requests
from lxml import etree
import re
from multiprocessing.dummy import Pool
#需求:爬取梨视频的视频数据
headers = {
'User-Agent':'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36'
}
#原则:线程池处理的是阻塞且较为耗时的操作
#对下述url发起请求解析出视频详情页的url和视频的名称
url = 'https://www.pearvideo.com/category_5'
page_text = requests.get(url=url,headers=headers).text
tree = etree.HTML(page_text)
li_list = tree.xpath('//ul[@id="listvideoListUl"]/li')
urls = [] #存储所有视频的链接and名字
for li in li_list:
detail_url = 'https://www.pearvideo.com/'+li.xpath('./div/a/@href')[0]
name = li.xpath('./div/a/div[2]/text()')[0]+'.mp4'
#对详情页的url发起请求
detail_page_text = requests.get(url=detail_url,headers=headers).text
#从详情页中解析出视频的地址(url)
ex = 'srcUrl="(.*?)",vdoUrl'
video_url = re.findall(ex,detail_page_text)[0]
dic = {
'name':name,
'url':video_url
}
urls.append(dic)
#对视频链接发起请求获取视频的二进制数据,然后将视频数据进行返回
def get_video_data(dic):
url = dic['url']
print(dic['name'],'正在下载......')
data = requests.get(url=url,headers=headers).content
#持久化存储操作
with open(dic['name'],'wb') as fp:
fp.write(data)
print(dic['name'],'下载成功!')
#使用线程池对视频数据进行请求(较为耗时的阻塞操作)
pool = Pool(4)
pool.map(get_video_data,urls)
pool.close()
pool.join()
多线程爬取梨视频的热门视频数据
import requests
import time
from multiprocessing.dummy import Pool
from lxml import etree
start_time = time.time()
#只有get_page是一个阻塞的操作
name_list = [0,1,2]
headers = {
'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.141 Safari/537.36'
}
#实例化一个线程对象
current_page = requests.get(url='https://www.pearvideo.com/category_5',headers=headers).text
with open('current_page.html','w',encoding='utf-8') as fp:
fp.write(current_page)
tree = etree.HTML(current_page)
li_list = tree.xpath('//*[@id="listvideoListUl"]/li')
def get_page(k):
title = li_list[k].xpath('./div/a/@href')
print('title = ')
print(title)
current_url = 'https://www.pearvideo.com/'+title[0]
headers = {
'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.141 Safari/537.36'
}
current_page = requests.get(url=current_url,headers=headers).text
with open('current_page'+str(k)+'.txt','w',encoding='utf-8') as file_obj:
file_obj.write(current_page)
pool = Pool(3)
pool.map(get_page,name_list)
#将列表中每一个列表元素传递给get_page进行处理
pool.close()
pool.join()
end_time = time.time()
print(end_time-start_time)