Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Python Scrapy Library

Python Scrapy Library

Scrapy is a powerful Python crawling framework designed specifically for scraping web page data and extracting information.

Scrapy is often used for applications such as data mining, information processing, or storing historical data.

Scrapy has many useful built-in features, such as handling requests, tracking state, handling errors, and handling request rate limits, making it well suited to efficient, distributed web crawling.

Unlike simple crawling libraries (such as requests and BeautifulSoup), Scrapy is a full-featured crawling framework with high extensibility and flexibility, suitable for complex and large-scale web scraping tasks.

Scrapy official site:https://scrapy.org/。

Scrapy features and introduction:https://www.runoob.com/w3cnote/scrapy-detail.html。

Scrapy architecture diagram (the green lines show the data flow):

Scrapy's work is based on the following core components:

Install Scrapy

Before using Scrapy you need to install it; we use pip:


pip install scrapy

Scrapy project structure

A Scrapy project is a structured directory containing several folders and modules designed to help you organize your crawler code.

Scrapy uses command-line tools to create and manage crawler projects. You can create a new Scrapy project with the following command:


scrapy startproject myproject

This creates a project named myproject with roughly the following structure:

myproject/
    scrapy.cfg            # 项目的配置文件
    myproject/            # 项目源代码文件夹
        __init__.py
        items.py          # 定义抓取的数据结构
        middlewares.py    # 定义中间件
        pipelines.py      # 定义数据处理管道
        settings.py       # 项目的设置文件
        spiders/           # 存放爬虫代码的文件夹
            __init__.py
            myspider.py   # 自定义的爬虫代码

Write a simple Scrapy spider

The following is a basic Scrapy spider example showing how to scrape data from a web page.

We create a crawler project:


scrapy startproject runoob_test_spiders

Running the command above produces the following output if it succeeds:

templates/project', created in:/Users/Runoob/runoob-test/runoob_test_spiders

You can start your first spider with:
    cd runoob_test_spiders
    scrapy genspider example example.com

The generated project structure is as follows:

Then enter that directory:

cd runoob_test_spiders

Next, create a spider with the scrapy genspider command:


scrapy genspider douban_spider movie.douban.com

The directory structure is as follows:

A file named douban_spider.py is generated in the runoob_test_spiders directory, with the following code:

Example

import

scrapy

class

DoubanSpiderSpider

(

scrapy.

Spider

)

:

    name

=

"douban_spider"

    allowed_domains

=

[

"movie.douban.com"

]

    start_urls

=

[

"https://movie.douban.com"

]

   

def

parse

(

self

,

response

)

:

       

pass

Code explanation:

Write the spider code

There are a few things to note before writing the spider code:

Modify the settings.py configuration

Add the following configuration to settings.py to simulate browser requests and get around anti-crawling mechanisms:

# 设置 User-Agent
USER_AGENT = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36'

# Ignore robots.txt rules
ROBOTSTXT_OBEY = False

# Set download delay to avoid too fast requests
DOWNLOAD_DELAY = 2

# Enable automatic rate limiting extension
AUTOTHROTTLE_ENABLED = True
AUTOTHROTTLE_START_DELAY = 2
AUTOTHROTTLE_MAX_DELAY = 5

In the spider code, add custom request headers (such as User-Agent and Referer) to further simulate browser behavior.

Open the douban_spider.py file and change its contents to the following:

Example

import

scrapy

class

DoubanSpider

(

scrapy.

Spider

)

:

    name

=

"douban_spider"

    start_urls

=

[

       

'https://movie.douban.com/top250'

,

   

]

   

def

start_requests

(

self

)

:

        headers

=

{

           

'User-Agent'

:

'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36'

,

           

'Referer'

:

'https://movie.douban.com/'

,

       

}

       

for

url

in

self

.

start_urls

:

           

yield

scrapy.

Request

(

url

,

headers

=

headers

,

callback

=

self

.

parse

)

   

def

parse

(

self

,

response

)

:

       

for

movie

in

response.

css

(

'div.item'

)

:

           

yield

{

               

'title'

: movie.

css

(

'span.title::text'

)

.

get

(

)

,

               

'rating'

: movie.

css

(

'span.rating_num::text'

)

.

get

(

)

,

               

'quote'

: movie.

css

(

'span.inq::text'

)

.

get

(

)

,

           

}

       

Handle pagination

        next_page

=

response.

css

(

'span.next a::attr(href)'

)

.

get

(

)

       

if

next_page

is

not

None

:

           

yield

response.

follow

(

next_page

,

callback

=

self

.

parse

)

Code analysis:

  1. name = "douban_spider": Define the name of the spider.

  2. start_urls: Define the initial URL where the spider starts crawling (the Douban Movie Top 250 page).

  3. parse Method:

  4. Use CSS selectors to extract the title, rating and summary of each movie.

  5. span.title::text: Extract the movie title.

  6. span.rating_num::text: Extract the movie rating.

  7. span.inq::text: Extract the movie summary.

  8. -

    Use CSS selectors to extract the title, rating and summary of each movie.

    -

    span.title::text: Extract the movie title.

    -

    span.rating_num::text: Extract the movie rating.

    -

    span.inq::text: Extract the movie summary.

    1. Pagination handling:

    2. Use span.next a::attr(href) Extract the link to the next page.

    3. If a next page exists, use response.follow to continue crawling.

    4. -

      Use span.next a::attr(href) Extract the link to the next page.

      -

      If a next page exists, use response.follow to continue crawling.

      Run the following command in the terminal to start the spider:

      
      scrapy crawl douban_spider -o douban_movies.csv
      

      This starts the spider and saves the extracted data to the douban_movies.csv file.

      Note: the above is for learning purposes only; when crawling data, obey the rules in the target site's robots.txt file.


      // 2022-01-01 00:00:00 GMT

      1. Spider methods

      Method Names Description Example
      start_requests() Generate the initial requests; you can customize request headers, request methods, etc. yield scrapy.Request(url, callback=self.parse)
      parse(response) Process the response and extract data; the core method of a spider. yield {'title': response.css('h1::text').get()}
      follow(url, callback) Automatically handle relative URLs and generate new requests, used for pagination or link following. yield response.follow(next_page, callback=self.parse)
      closed(reason) Called when the spider closes, used to clean up resources or write logs. def closed(self, reason): print('Spider closed:', reason)
      log(message) Log a message. self.log('This is a log message')

      2. Data extraction methods

      Method Names Description Example
      response.css(selector) Extract data with CSS selectors. title = response.css('h1::text').get()
      response.xpath(selector) Extract data with XPath selectors. title = response.xpath('//h1/text()').get()
      get() From the SelectorList Extract the first matching result (as a string) from . title = response.css('h1::text').get()
      getall() From the SelectorList Extract all matching results (as a list) from . titles = response.css('h1::text').getall()
      attrib Extract an attribute of the current node. link = response.css('a::attr(href)').get()

      3. Request and response methods

      Method Names Description Example
      scrapy.Request(url, callback, method, headers, meta) Create a new request. yield scrapy.Request(url, callback=self.parse, headers=headers)
      response.url Get the URL of the current response. current_url = response.url
      response.status Get the response status code. if response.status == 200: print('Success')
      response.meta Get the extra data passed along with the request. value = response.meta.get('key')
      response.headers Get the response headers. content_type = response.headers.get('Content-Type')

      4. Middleware and pipeline methods

      Method Names Description Example
      process_request(request, spider) Process the request before it is sent (downloader middleware). request.headers['User-Agent'] = 'Mozilla/5.0'
      process_response(request, response, spider) Process the response after it returns (downloader middleware). if response.status == 403: return request.replace(dont_filter=True)
      process_item(item, spider) Process the extracted data (pipeline). if item['price'] < 0: raise DropItem('Invalid price')
      open_spider(spider) Called when the spider starts (pipeline). def open_spider(self, spider): self.file = open('items.json', 'w')
      close_spider(spider) Called when the spider closes (pipeline). def close_spider(self, spider): self.file.close()

      5. Tools and extension methods

      Method Names Description Example
      scrapy shell Launch an interactive shell for debugging and testing selectors. scrapy shell 'http://example.com'
      scrapy crawl Run a specified spider. scrapy crawl myspider -o output.json
      scrapy check Check the correctness of the spider code. scrapy check
      scrapy fetch Download the content of a specified URL. scrapy fetch 'http://example.com'
      scrapy view View a page downloaded by Scrapy in the browser. scrapy view 'http://example.com'

      6. Common settings (settings.py)

      Setting Description Example
      USER_AGENT Set the User-Agent in the request headers. USER_AGENT = 'Mozilla/5.0'
      ROBOTSTXT_OBEY Whether to obey the robots.txt rules. ROBOTSTXT_OBEY = False
      DOWNLOAD_DELAY Set a download delay to avoid requesting too quickly. DOWNLOAD_DELAY = 2
      CONCURRENT_REQUESTS Set the number of concurrent requests. CONCURRENT_REQUESTS = 16
      ITEM_PIPELINES Enable pipelines. ITEM_PIPELINES = {'myproject.pipelines.MyPipeline': 300}
      AUTOTHROTTLE_ENABLED Enable the auto-throttling extension. AUTOTHROTTLE_ENABLED = True

      7. Other common methods

      Method Names Description Example
      response.follow_all(links, callback) Batch-process links and generate requests. yield from response.follow_all(links, callback=self.parse)
      response.json() Parse the response content as JSON. data = response.json()
      response.text Get the text content of the response. html = response.text
      response.selector Get the response content's Selector object. title = response.selector.css('h1::text').get()

      The table above lists the commonly used Scrapy methods and what they do. These methods cover every aspect of spider development, including request generation, data extraction, middleware handling and pipeline operations. By mastering them you can write and manage Scrapy spiders efficiently. For more detailed functionality, see the Scrapy official documentation。


      Method usage examples

      1. start_requests()

      start_requests() The method is the entry point of a Scrapy spider and is used to generate the initial requests. The spider's starting URL is usually defined in this method.

      Example

      import

      scrapy

      class

      MySpider

      (

      scrapy.

      Spider

      )

      :

          name

      =

      'myspider'

         

         

      def

      start_requests

      (

      self

      )

      :

              urls

      =

      [

                 

      'http://example.com/page1'

      ,

                 

      'http://example.com/page2'

      ,

             

      ]

             

      for

      url

      in

      urls:

                 

      yield

      scrapy.

      Request

      (

      url

      =

      url

      ,

      callback

      =

      self

      .

      parse

      )

      2. parse()

      parse() The method is the default response handler, used to parse the response and extract data or generate new requests.

      Example

      def

      parse

      (

      self

      ,

      response

      )

      :

         

      Extract the page title

          title

      =

      response.

      css

      (

      'title::text'

      )

      .

      get

      (

      )

         

      yield

      {

             

      'title'

      : title

         

      }

      3. parse_item()

      parse_item() The method parses the response for a single Item; it is usually used to extract structured data.

      Example

      def

      parse_item

      (

      self

      ,

      response

      )

      :

          item

      =

      {

      }

          item

      [

      'name'

      ]

      =

      response.

      css

      (

      'div.name::text'

      )

      .

      get

      (

      )

          item

      [

      'price'

      ]

      =

      response.

      css

      (

      'div.price::text'

      )

      .

      get

      (

      )

         

      yield

      item

      4. follow()

      follow() The method generates new requests and handles responses automatically; it is usually used to follow links.

      Example

      def

      parse

      (

      self

      ,

      response

      )

      :

         

      for

      link

      in

      response.

      css

      (

      'a::attr(href)'

      )

      :

             

      yield

      response.

      follow

      (

      link

      ,

      self

      .

      parse_item

      )

      5. yield

      yield The keyword is used to generate a request or an Item and pass it to the Scrapy engine for processing.

      Example

      def

      parse

      (

      self

      ,

      response

      )

      :

         

      yield

      {

             

      'title'

      : response.

      css

      (

      'title::text'

      )

      .

      get

      (

      )

         

      }

      6. Item

      Item The class defines data structures, usually used to store data extracted from web pages.

      Example

      import

      scrapy

      class

      MyItem

      (

      scrapy.

      Item

      )

      :

          name

      =

      scrapy.

      Field

      (

      )

          price

      =

      scrapy.

      Field

      (

      )

      7. ItemLoader

      ItemLoader The class loads and fills Item objects, simplifying the data extraction and processing workflow.

      Example

      from

      scrapy.

      loader

      import

      ItemLoader

      from

      myproject.

      items

      import

      MyItem

      def

      parse

      (

      self

      ,

      response

      )

      :

          loader

      =

      ItemLoader

      (

      item

      =

      MyItem

      (

      )

      ,

      response

      =

      response

      )

          loader.

      add_css

      (

      'name'

      ,

      'div.name::text'

      )

          loader.

      add_css

      (

      'price'

      ,

      'div.price::text'

      )

         

      yield

      loader.

      load_item

      (

      )

      8. Request

      Request The class generates HTTP request objects, usually used to define a request's URL, callback method, etc.

      Example

      import

      scrapy

      def

      parse

      (

      self

      ,

      response

      )

      :

         

      yield

      scrapy.

      Request

      (

      url

      =

      'http://example.com/page3'

      ,

      callback

      =

      self

      .

      parse_item

      )

      9. Response

      Response The class represents an HTTP response object, containing the HTML content returned by the server, the status code and other information.

      Example

      def

      parse

      (

      self

      ,

      response

      )

      :

         

      print

      (

      response.

      status

      )

       

      Print the response status code

         

      print

      (

      response.

      body

      )

         

      Print the response content

      10. Selector

      Selector The class extracts data from HTML or XML documents and supports XPath and CSS selectors.

      Example

      def

      parse

      (

      self

      ,

      response

      )

      :

          title

      =

      response.

      xpath

      (

      '//title/text()'

      )

      .

      get

      (

      )

         

      yield

      {

             

      'title'

      : title

         

      }

      11. CrawlSpider

      CrawlSpider is a special Spider class used to handle complex crawling rules and link following.

      Example

      from

      scrapy.

      spiders

      import

      CrawlSpider

      ,

      Rule

      from

      scrapy.

      linkextractors

      import

      LinkExtractor

      class

      MyCrawlSpider

      (

      CrawlSpider

      )

      :

          name

      =

      'mycrawlspider'

          allowed_domains

      =

      [

      'example.com'

      ]

          start_urls

      =

      [

      'http://example.com'

      ]

          rules

      =

      (

              Rule

      (

      LinkExtractor

      (

      allow

      =

      (

      'page/\d+'

      ,

      )

      )

      ,

      callback

      =

      'parse_item'

      )

      ,

         

      )

         

      def

      parse_item

      (

      self

      ,

      response

      )

      :

             

      yield

      {

                 

      'title'

      : response.

      css

      (

      'title::text'

      )

      .

      get

      (

      )

             

      }

      12. LinkExtractor

      LinkExtractor The class extracts links from a response, usually used to follow links on a page automatically.

      Example

      from

      scrapy.

      linkextractors

      import

      LinkExtractor

      def

      parse

      (

      self

      ,

      response

      )

      :

          extractor

      =

      LinkExtractor

      (

      allow

      =

      (

      'page/\d+'

      ,

      )

      )

          links

      =

      extractor.

      extract_links

      (

      response

      )

         

      for

      link

      in

      links:

             

      yield

      scrapy.

      Request

      (

      link.

      url

      ,

      callback

      =

      self

      .

      parse_item

      )

      13. Pipeline

      Pipeline The class processes scraped data, usually for cleaning, storing and similar operations.

      Example

      class

      MyPipeline:

         

      def

      process_item

      (

      self

      ,

      item

      ,

      spider

      )

      :

             

      Process item data

             

      return

      item

      14. Middleware

      Middleware The class is a middleware for requests and responses, usually used to modify request headers, handle exceptions, etc.

      Example

      class

      MyMiddleware:

         

      def

      process_request

      (

      self

      ,

      request

      ,

      spider

      )

      :

             

      Modify request headers

              request.

      headers

      [

      'User-Agent'

      ]

      =

      'MyCustomUserAgent'

             

      return

      None