练习---爬取时光网电视剧TOP100的电影名,用同步和异步两种方式,并对比完成速度

from gevent import monkey
monkey.patch_all()

import requests,time,gevent
from bs4 import BeautifulSoup
from gevent.queue import Queue

res = requests.get('http://www.mtime.com/top/tv/top100/')
html = res.text
bs = BeautifulSoup(html,'html.parser')
page = bs.find(id='PageNavigator').find_all('a')
url_list = []
url_list.append('http://www.mtime.com/top/tv/top100/')
for p in page:
    try:
        url_list.append(p['href'])
    except KeyError:
        pass
#print(url_list)



#非多协程的时间
start = time.time()
def crawler(url):
    res = requests.get(url)
    #print(res.status_code)
    html = res.text
    bs = BeautifulSoup(html, 'html.parser')
    movies = bs.find(class_="colm").find(class_='top_list').find('ul').find_all('li')
    for movie in movies:
        name = movie.find(class_='px14 pb6').find('a').text
        print(name)
for url in url_list:
    crawler(url)
end = time.time()
interval = end - start


#多协程的时间
start2 = time.time()
work = Queue()
for url in url_list:
    work.put_nowait(url)
    #把url放进队列
def crawler(url):
    while not work.empty():
        url = work.get_nowait()
        res = requests.get(url)
        #print(res.status_code)
        html = res.text
        bs = BeautifulSoup(html, 'html.parser')
        movies = bs.find(class_="colm").find(class_='top_list').find('ul').find_all('li')
        for movie in movies:
            name = movie.find(class_='px14 pb6').find('a').text
            print(name)
task_list = []
for x in range(5):
#同时建立了5个爬虫,越多越快
    task = gevent.spawn(crawler,url)
    task_list.append(task)
gevent.joinall(task_list)
end2 = time.time()
interval2 = end2 - start2
print("\n"+'同步爬虫时间为:'+str(interval))
print('5个异步爬虫时间为'+str(interval2))

 

评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值