練習介紹
要求:
請使用多協程和隊列,爬取時光網電視劇TOP100的數據(劇名、導演、主演和簡介),并用csv模塊將數據存儲下來。
時光網TOP100鏈接:http://www.mtime.com/top/tv/top100/
目的:
1.練習掌握gevent的用法
2.練習掌握queue的用法
from gevent import monkey#gevent從庫里導入monkey模塊
monkey.patch_all()#能把程序變成協作式運行,就是可以幫助程序實現異步
import gevent,time,requests,csv
from gevent.queue import Queue#gevent從庫里導入queue模塊
from bs4 import BeautifulSoup
work=Queue()#創建隊列對象,并賦值給work
url_1='http://www.mtime.com/top/tv/top100/'
work.put_nowait(url_1)#用put_nowait()函數把url_1也就是第一頁的網址放進隊列里
for i in range(2,11):
url_2='http://www.mtime.com/top/tv/top100/index-{}.html'.format(i)#2-10頁的網址循環遍歷
work.put_nowait(url_2)#用put_nowait()函數把2-10頁的網址都放進隊列里。
def crawler():
headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64)\
AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36'}
while not work.empty():#當隊列不是空的時候,就執行下面的程序
url=work.get_nowait()#get_nowait()函數可以把隊列里的網址都取出。
res=requests.get(url,headers=headers)#用requests.get()函數抓取網址。
html=res.text
soup=BeautifulSoup(html,'html.parser')
items=soup.find_all('div',class_='mov_con')
for item in items:
name=item.find('a').text
datas=item.find_all('p')
for data in datas:
if data.text[:2]=='導演':
director=data.text[3:].strip()
elif data.text[:2]=='主演':
actor=data.text[3:].strip()
else:
remarks = data.text.strip()
writer.writerow([name,director,actor,remarks])
csv_file=open('TVtop100.csv','w',newline='',encoding='utf-8-sig')
writer=csv.writer(csv_file)
writer.writerow(['電視劇名','導演','主演','簡介'])
tasks_list=[]#創建空的任務列表
for x in range(3):#相當于創建了3個爬蟲
task=gevent.spawn(crawler)#用gevent.spawn()函數創建執行crawler()函數的任務
tasks_list.append(task)
gevent.joinall(tasks_list)#用gevent.joinall方法,執行任務列表里的所有任務,就是讓爬蟲開始爬取網站。
csv_file.close()
更多文章、技術交流、商務合作、聯系博主
微信掃碼或搜索:z360901061

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