寫python協程時使用gevent模塊和queue模塊可以大大提高爬蟲速度。在同時爬取多個網站時,原來用for循環一個網站一個網站按循序順序爬,就像先燒飯后燒菜,兩個步驟異步進行。使用多協程可以讓爬蟲自己選擇爬取順序,就像邊燒飯邊燒菜,兩個步驟同步進行,速度自然快了。
不多說了,來看下代碼吧:
from gevent import monkey
monkey.patch_all()
#打上多協程布丁,下面的程序就可以執行多協程了
import requests,gevent,csv
from gevent.queue import Queue
from bs4 import BeautifulSoup
#把所有URL都放到一個列表里:
url_list=[]
i=1
for i in range(10):
i=i+1
url='http://www.mtime.com/top/tv/top100/index-'+str(i)+'.html'
url_list.append(url)
#第一個url和別的不一樣,需要單獨加入
url_0='http://www.mtime.com/top/tv/top100/'
url_list.append(url_0)
headers={
'User-Agent':
}
csv_file=open('時光網電影列表.csv','a+',newline='',encoding='utf-8')
writer=csv.writer(csv_file)
file_head=['電影名稱','導演','主演','簡介']
writer.writerow(file_head)
def list(movies):
for movie in movies:
title=movie.find('h2',class_="px14 pb6").find('a').text
acts=movie.find_all('p')
try:
dic=acts[0].text
except IndexError:
dic='none'
try:
actor=acts[1].text
except IndexError:
actor='none'
try:
bief=movie.find('p',class_="mt3").text
except AttributeError:
bief='none'
writer.writerow([title,dic,actor,bief])
#所有url都放到‘不用等’房間里:
work=Queue()
for url in url_list:
work.put_nowait(url)
#爬蟲對象:
def crawler():
while not work.empty():
url=work.get_nowait()
res=requests.get(url,headers=headers)
soup=BeautifulSoup(res.text,'html.parser')
movies=soup.find_all('div',class_="mov_con")
list(movies)
print(url,work.qsize(),res.status_code)
#建立多協程任務,任務不用建太多,2個就夠,太多的話對方服務器承受不了
tasks_list=[]
for x in range(2):
task=gevent.spawn(crawler)
tasks_list.append(task)
gevent.joinall(tasks_list)
csv_file.close()
更多文章、技術交流、商務合作、聯系博主
微信掃碼或搜索:z360901061

微信掃一掃加我為好友
QQ號聯系: 360901061
您的支持是博主寫作最大的動力,如果您喜歡我的文章,感覺我的文章對您有幫助,請用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點擊下面給點支持吧,站長非常感激您!手機微信長按不能支付解決辦法:請將微信支付二維碼保存到相冊,切換到微信,然后點擊微信右上角掃一掃功能,選擇支付二維碼完成支付。
【本文對您有幫助就好】元
