python多协程爬虫示例

发布时间:2020-06-26 11:17:10 作者:wx5d72071a58c07
来源:网络 阅读:521

写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('h3',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()
推荐阅读:
  1. python协程的理解
  2. python协程的示例分析

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

python爬虫

上一篇:sed命令练习

下一篇:java怎么用函数输出

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》