如题,同步运行就是python按照代码逐一运行,如向服务器发送请求,前一个请求得到回应后,才会发起后一个请求,而异步可以在前一个请求在等待回应的时候,就可以发起后一个请求,甚至后两个请求,等到第一个请求得到响应后再回来处理,即可以在多个任务之间来回切换运行,这样就提高了python跑程序的效率,如任务量大,抓取网页多,可能会缩短大量时间。但是,这两种运行方式有一个共同点,那就是同一时刻只能执行一个任务。现分别以同步与异步的方法抓取了时光网Top100的电影(共10个网页),发现异步方式确实一定程度提高了代码运行效率,但是值得注意的是,应为异步运行每次的流程与服务器响应有关,所以每次的运行流程稍有不同,在代码中我用print打印了整个抓取流程,列出代码如下:
同步运行:
import requests
from bs4 import BeautifulSoup
import openpyxl
import time
start=time.time()
headers={
'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/77.0.3865.90 Safari/537.36'
}
url1='http://www.mtime.com/top/movie/top100/'#爬第1页
res=requests.get(url1,headers=headers)
print(res.status_code)
soup=BeautifulSoup(res.text,'html.parser')
mov_con=soup.find_all('div',class_='mov_con')
num=soup.find_all('div',class_='number')
list=[]
for i in mov_con:
protagonist=[]
name=i.find('h2').text
director=i.find_all('p')[0].find('a').text
protagonist_con=i.find_all('p')[1].find_all('a')
for item in protagonist_con:
actor=item.text
protagonist.append(actor)
abstract=i.find_all('p')[3].text
list.append([name,director,','.join(protagonist),abstract])
for x in range(2,11):
url2='http://www.mtime.com/top/movie/top100/index-'+str(x)+'.html'#爬2-10页
res=requests.get(url2,headers=headers)
print(res.status_code)
soup=BeautifulSoup(res.text,'html.parser')
mov_con=soup.find_all('div',class_='mov_con')
for i in mov_con:
protagonist=[]
name=i.find('h2').text
director=i.find_all('p')[0].find('a').text
protagonist_con=i.find_all('p')[1].find_all('a')
for item in protagonist_con:
actor=item.text
protagonist.append(actor)
abstract=i.find('p',class_='mt3').text
#由于网页设计‘暴力云与送子鹳 Partly Cloudy (2009)’错误原因,abstract=i.find_all('p')[3].text报错
list.append([name,director,','.join(protagonist),abstract])#protagonist时列表不能直接写入excel的单元格,需要先把列表转换成字符串格式
wb=openpyxl.Workbook()
sheet=wb.active
sheet['A1']='剧名'
sheet['B1']='导演'
sheet['C1']='主演'
sheet['D1']='简介'
for i in list:
sheet.append(i)
wb.save('时光热榜电影.xlsx')
wb.close()
end=time.time()
print('耗时:',end-start)
异步运行(协程):
from gevent import monkey
monkey.patch_all()
import gevent,time,requests,openpyxl
from gevent.queue import Queue
from bs4 import BeautifulSoup
start=time.time()
headers={
'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/77.0.3865.90 Safari/537.36'
}
url_list=['http://www.mtime.com/top/movie/top100/']
for i in range(2,11):
url_list.append('http://www.mtime.com/top/movie/top100/index-'+str(i)+'.html')#生成待抓取网页列表
work=Queue()#创建、实例化队列对象
for url in url_list:
work.put_nowait(url)#把网页放进queue队列里
list =[]
def spider():
while not work.empty():#队列非空时
url=work.get_nowait()#在队列里取网页
res=requests.get(url,headers=headers)
print(url,res.status_code)
soup=BeautifulSoup(res.text,'html.parser')
mov_con=soup.find_all('div',class_='mov_con')
for i in mov_con:
protagonist=[]
name=i.find('h2').text
director=i.find_all('p')[0].find('a').text
protagonist_con=i.find_all('p')[1].find_all('a')
for item in protagonist_con:
actor=item.text
protagonist.append(actor)
abstract=i.find('p',class_='mt3').text
print([name,director,','.join(protagonist),abstract])
print('-------------------------------------------')
#由于网页设计‘暴力云与送子鹳 Partly Cloudy (2009)’错误原因,abstract=i.find_all('p')[3].text报错
list.append([name,director,','.join(protagonist),abstract])#protagonist时列表不能直接写入excel的单元格,需要先把列表转换成字符串格式
print('\n 换页\n')
task_list=[]#创建任务列表
for x in range(3):#创建3只爬虫
task=gevent.spawn(spider)#创建每个爬虫的任务,需要任务流程(spider函数)和任务所需资源(spider函数自变量,这里是不需要)
task_list.append(task)#任务组成任务列表
gevent.joinall(task_list)#任务列表加入协程,开始协程执行任务列表中的任务
wb=openpyxl.Workbook()
sheet=wb.active
sheet['A1']='剧名'
sheet['B1']='导演'
sheet['C1']='主演'
sheet['D1']='简介'
for i in list:
sheet.append(i)
wb.save('时光热榜电影.xlsx')
wb.close()
end=time.time()
print(end-start)
运行结果,异步运行耗时16.9s,同步运行耗时39.5s。显然,异步效率高于同步,但是异步有一个缺点就是抓取的页面不是按顺序响应的,即保存的电影顺序是响应速度快的在前,速度慢的在后,没有按照TOP100顺序来保存,所以我们应该根据抓取需求来选择抓取的方式是用同步还是异步。
另外,多协程抓取的对象过程为:url_list--------> task_list------->result_list----->sheet.append(result_list)