練習(xí)介紹
要求:
請(qǐng)使用多協(xié)程和隊(duì)列,爬取時(shí)光網(wǎng)電視劇TOP100的數(shù)據(jù)(劇名、導(dǎo)演、主演和簡(jiǎn)介),并用csv模塊將數(shù)據(jù)存儲(chǔ)下來(lái)。
時(shí)光網(wǎng)TOP100鏈接:http://www.mtime.com/top/tv/top100/
目的:
1.練習(xí)掌握gevent的用法
2.練習(xí)掌握queue的用法
from gevent import monkey#gevent從庫(kù)里導(dǎo)入monkey模塊
monkey.patch_all()#能把程序變成協(xié)作式運(yùn)行,就是可以幫助程序?qū)崿F(xiàn)異步
import gevent,time,requests,csv
from gevent.queue import Queue#gevent從庫(kù)里導(dǎo)入queue模塊
from bs4 import BeautifulSoup
work=Queue()#創(chuàng)建隊(duì)列對(duì)象,并賦值給work
url_1='http://www.mtime.com/top/tv/top100/'
work.put_nowait(url_1)#用put_nowait()函數(shù)把url_1也就是第一頁(yè)的網(wǎng)址放進(jìn)隊(duì)列里
for i in range(2,11):
url_2='http://www.mtime.com/top/tv/top100/index-{}.html'.format(i)#2-10頁(yè)的網(wǎng)址循環(huán)遍歷
work.put_nowait(url_2)#用put_nowait()函數(shù)把2-10頁(yè)的網(wǎng)址都放進(jìn)隊(duì)列里。
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():#當(dāng)隊(duì)列不是空的時(shí)候,就執(zhí)行下面的程序
url=work.get_nowait()#get_nowait()函數(shù)可以把隊(duì)列里的網(wǎng)址都取出。
res=requests.get(url,headers=headers)#用requests.get()函數(shù)抓取網(wǎng)址。
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]=='導(dǎo)演':
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(['電視劇名','導(dǎo)演','主演','簡(jiǎn)介'])
tasks_list=[]#創(chuàng)建空的任務(wù)列表
for x in range(3):#相當(dāng)于創(chuàng)建了3個(gè)爬蟲
task=gevent.spawn(crawler)#用gevent.spawn()函數(shù)創(chuàng)建執(zhí)行crawler()函數(shù)的任務(wù)
tasks_list.append(task)
gevent.joinall(tasks_list)#用gevent.joinall方法,執(zhí)行任務(wù)列表里的所有任務(wù),就是讓爬蟲開始爬取網(wǎng)站。
csv_file.close()
更多文章、技術(shù)交流、商務(wù)合作、聯(lián)系博主
微信掃碼或搜索:z360901061

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