大家好,我是天空之城,今天给大家带来小福利,用gevent多协程高效爬取海量数据
话不多说,代码如下
from gevent import monkey
monkey.patch_all()
import gevent,time,requests
from bs4 import BeautifulSoup
from gevent.queue import Queue
start = time.time()
header = {
'Referer': 'https://movie.douban.com/top250?start=1&filter=',
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; rv:46.0) Gecko/20100101 Firefox/46.0'}
url_list =[]
for i in range(0,225,25):
url='https://movie.douban.com/top250?start={}&filter='.format(str(i))
url_list.append(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=header)
film = res.text
#这里的res.text就是获取到的整个网页的所有源代码了,下面利用 'html.parser'模块进行网页数据的解析
soup = BeautifulSoup(film, 'html.parser')
#首先获取到了所有li标签下面的<‘div’,class_="item">标签,构成一个大的列表
items = soup.find_all("div",class_="item")
#对列表进行遍历,获取每一部电影的相关信息
for item in items:
xuhao=item.find('em').text #序号
title=item.find(class_="title").text #电影名称
pingfen=item.find(class_="rating_num").text #评分
comment=item.find(class_="inq") #评论
if comment==None:
comment=''
else:
comment = item.find(class_="inq").text # 评论
link=item.find('a')['href'] #网址
#打印一下我们获得的信息
print(xuhao,title,pingfen,comment,link)
task_list=[]
for x in range(5):
task=gevent.spawn(crawler)
task_list.append(task)
gevent.joinall(task_list)
获取数据截图如下