How to build a distributed crawler

Source: Internet
Author: User

Reproduced from:

http://python.jobbole.com/87823/

http://python.jobbole.com/87826/

http://python.jobbole.com/87833/
Theory Chapter Preface

This series of articles is planned to be divided into three chapters, which are theoretical articles, basic articles and practical articles. Theoretical article mainly for the construction of distributed reptiles and reserves of theoretical knowledge, based on the knowledge of theoretical articles to write a simple distributed crawler, the actual combat will take micro-blog as an example, to teach you to do a relatively complete and robust distributed micro-blog crawler. Through these three articles, I hope you can master how to build a distributed crawler , and can extrapolate celery for other scenes except reptiles. While basically blogging is about using Scrapyd or Scrapy-redis to build distributed reptiles, this series of articles will tell you how to build a robust, scalable, scalable, distributed crawler with Requests+celery in another perspective.

This series of articles belongs to the Reptile advanced article, the expectation audience is has the Python basic knowledge and the programming ability, has the reptile experience and wants to ascend oneself schoolmate. Small white If interested, also can look, do not understand the words, can wait for a certain basis and experience back to look again.

Another point is that this series of articles is not designed to build a distributed crawler framework or distributed task scheduling framework, but to use the existing distributed task scheduling tools to implement the distributed crawler , so please light spray. Distributed Crawler Overview What is a distributed crawler.
In layman's terms, distributed crawler is a multiple-machine spider multiple URLs at the same time to deal with the problem, distributed way can greatly improve the crawl efficiency of the program. Problems to be considered in constructing distributed crawler
(1) How to ensure that multiple machines crawl the same URL at the same time.
(2) If a node hangs, will not affect other nodes, how the task continues.
(3) since it is distributed, how to ensure the scalability and scalability of the architecture. How to allocate and dispatch resource in different priority crawl task.

Based on the above problems, I choose to use celery as distributed task Scheduling tool, which is the core module of task and resource scheduling in distributed crawler. It will send all tasks through the message queue to each distributed node for execution, so it is good to ensure that the URL will not be repeatedly crawled, it detects the worker hangs out, will try to resend the task information to other worker, so that the second problem can be resolved Celery with task routing, we can run different crawl tasks on different nodes according to the actual situation (I will talk about it in the actual combat article). This article is mainly to take you to understand all aspects of celery (have celery relevant experience and Daniel can skip the celery knowledge reserve celery Basic explanation

According to the introduction of celery official website

Celery is a simple, flexible and reliable distributed system that handles a large number of messages, and provides the necessary tools to maintain such a system. It is a task queue that focuses on real-time processing and also supports task scheduling.

The following are some of the core knowledge of celery: translation is called a middleman. It is a message transmission middleware, can be understood as a mailbox. Whenever an application invokes a celery asynchronous task, a message is passed to broker, and the celery worker takes the message and executes the program. This is actually a bridge between consumers and producers. Backend: Usually the message sent by the program, the end of the hair, may not know when the other party accepted. To do this, celery implements a backend for storing the messages and some of the messages and results that celery executes. An example of a Worker:celery class is the role of performing various tasks. Note that Windows does not support celery worker after celery3.1.25. Producer: Sends a task and passes it to a timed task implemented by the broker Beat:celery. It can be interpreted as a producer, because it is also timed to send a task to worker execution through a network call. Note that celery is not supported for timed tasks on Windows.

The following is a schematic diagram of celery, which should be better understood with the words above

Celery architecture Diagram

Since celery is only a task queue, rather than a true message queue, it does not have the ability to store data, so broker and backend need third-party tools to store information, celery officially recommend RABBITMQ and Redis, In addition MongoDB can also be as broker or backend, may not be very stable, we choose Redis here as broker and backend.

About Redis installation and configuration can see the actual example here

First install celery Python pip install celery

1 Pip Install celery

We give an example from the official website to explain and expand it. First in the project root, I create a new project called Celerystudy, then switch to the project directory, create a new file tasks.py, and then enter the following code Python from celery import celery app = celery (' Tasks ', broker= ' redis://: ' @223.129.0.190:6379/2 ', backend= ' redis://: ' @223.129.0.190:6379/3 ') @app. Task def add (x, Y): return x + y

1 2 3 4 5 6 7 From celery import celery app = celery (' tasks ', broker = ' redis://: ' @223.129.0.190:6379/2 ', backend = ' redis://: ' ' @223.129.0.190:6379/3 ') @ App. Task def add (x, y): return x + y

Here I'll go over the code: we instantiate a celery object by App=celery (), and in this process we specify its broker, which is Redis DB 2, and its backend, Redis db3, Broker and backend are probably connected in such a way that Python redis://:p assword@hostname:port/db_number

1 Redis://: password @ hostname:port/db_number

And then you define an add function, and the emphasis is @app.task, which in my opinion is the add ()
Registered as a service-like thing
that could have been decorated by a locally called function, it could be invoked over the network. The app in this tasks.py is a worker. It can have a lot of tasks, such as the task function add here. We then execute Python celery-a tasks worker-l info by switching to the project root directory at the command line

1 celery-a Tasks Worker-l Info

After the startup is successful, this is what the following image looks like

Celery's worker started successfully

Here I say the meaning of each parameter,-a specifies the file module of the app (that is, the celery instance), and our app is in tasks.py, so here's the tasks;worker, which means there's a way to run the worker in the current way. Yes, such as running a timed task does not specify the worker this keyword; -L info indicates that the worker node has a log level of info, more about the parameters for starting the worker (such as-C,-Q, etc.) please use the Python celery worker--help

1 Celery worker--help

To view

Once the worker is started, we can call the Add function over the network. This is the way we distribute and consume URLs in a later distributed crawler build. Switch to the project root directory at the command line, and then open the Python interactive side Python from tasks import add rs = Add.delay (2, 2) # The Add.delay here is to send the task over the network call to the worker performing the add

1 2 From tasks import Add rs = Add. Delay (2, 2) # The Add.delay here is to send the task over the network call to the worker performing the add

At this point we can see the task and the results of the calculation in the worker interface. Python [2017-05-19 14:22:43,038:info/mainprocess] Received Task:tasks.add[c0dfcd0b-d05f-4285-b944-0a8aba3e7e61] # Tasks received by worker [2017-05-19 14:22:43,065:info/mainprocess] Task Tasks.add[c0dfcd0b-d05f-4285-b944-0a8aba3e7e61] Succeeded in 0.025274309000451467s:4 # execution results

1 2 3 [2017-05-19 14:22:43, 038:info/mainprocess] Received Task:tasks. Add [c0dfcd0b-d05f-4285-b944-0a8aba3e7e61] # Worker receives task [2017-05-19 14:22:43, 065:info/mainproc ESS] Task tasks. Add [C0dfcd0b-d05f-4285-b944-0a8aba3e7e61] succeeded in 0.025274309000451467s:4 # execution results

Here is the asynchronous call, and if we need to return the result, then the ready state of RS will be true. Add no effect here, but imagine that if we were calling a comparison of time IO tasks, then the asynchronous task would be more valuable to Python RS # <asyncresult: C0dfcd0b-d05f-4285-b944-0a8aba3e7e61> Rs.ready () # True indicates that the results have been returned Rs.status # ' SUCCESS ' task execution status, failure or success rs.successful ( ) # True Indicates the result of a successful Rs.result # 4 Rs.get () # 4 returns results <celery.backends.redis.redisbackend object at 0x30033ec> #这里我 Backend the results are stored in Redis.

1 2 3 4 5 6 7 8 9 RS # <asyncresult:c0dfcd0b-d05f-4285-b9 44-0a8aba3e7e61>   Rs. Ready () # True indicates that the result has been returned   Rs. Status # ' SUCCESS ' task execution status, failure or success   Rs. Successful () # True indicates execution success   Rs. Result # 4 Returns the results   Rs. Get () # 4 Returns the result   < celery. Backends. Redis. Redisbackend object at 0x30033ec > #这里我们backend results are stored in Redis

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.