Python Scrapy Library
Scrapy is a powerful Python web scraping framework specifically designed for crawling web page data and extracting information.
Scrapy is often used for data mining, information processing, or storing historical data and other applications.
Scrapy has many built-in useful features, such as handling requests, tracking states, handling errors, handling request rate limits, etc., making it very suitable for efficient, distributed web crawling.
Unlike simple scraping libraries (such as requests and BeautifulSoup), Scrapy is a full-featured scraping framework with high scalability and flexibility, suitable for complex and large-scale web scraping tasks.
Scrapy Official Website: https://scrapy.org/.
Scrapy Features and Introduction: https://www.runoob.com/w3cnote/scrapy-detail.html.
Scrapy Architecture Diagram (green lines represent data flow):

Scrapy’s work is based on the following core components:
- Spider: Spider class, used to define how to extract data from web pages and how to follow links on the page.
- Item: Used to define and store scraped data. Equivalent to a data model.
- Pipeline: Used to process scraped data, commonly used for cleaning, storing data, and other operations.
- Middleware: Used to handle requests and responses, can be used to set proxies, handle cookies, user agents, etc.
- Settings: Used to configure various settings of the Scrapy project, such as request delay, concurrent request count, etc.
Installing Scrapy
Section titled “Installing Scrapy”Before using Scrapy, you need to install it first. Use pip to install:
Scrapy Project Structure
Section titled “Scrapy Project Structure”A Scrapy project is a structured directory containing multiple folders and modules designed to help you organize your spider code.
Scrapy uses command-line tools to create and manage spider projects. You can use the following command to create a new Scrapy project:
This will create a project named myproject with the following project structure:
Writing a Simple Scrapy Spider
Section titled “Writing a Simple Scrapy Spider”The following is a basic Scrapy spider example demonstrating how to scrape data from a web page.
Let’s create a spider project:
Executing the above command, if successful, will output:
The generated project structure is as follows:

Then enter the directory:
Next, create a spider using the scrapy genspider command:
The directory structure is as follows:

A file named douban_spider.py is generated under the runoob_test_spiders directory with the following code:
Example
Section titled “Example”Code Explanation:
name: Defines the spider’s name, must be unique.allowed_domains: Restricts the spider’s access domain, preventing the spider from crawling pages on other domains.start_urls: Defines the spider’s starting pages. The spider will begin crawling from these pages.parse: Theparsemethod is the core part of each spider, used to process the response and extract data. It receives aresponseobject representing the page content returned by the server.
Writing Spider Code
Section titled “Writing Spider Code”Before writing spider code, we need to note a few points:
- Websites like Douban may detect spider behavior. It is recommended to set USER_AGENT and DOWNLOAD_DELAY to simulate normal user behavior.
- When scraping data, please comply with the target website’s robots.txt file regulations and avoid putting excessive pressure on the server.
- Frequent crawling may trigger IP bans.
Modifying settings.py Configuration
Section titled “Modifying settings.py Configuration”Add the following configuration in settings.py to simulate browser requests and bypass anti-scraping mechanisms:
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 modify its content as follows:
Example
Section titled “Example”Code Analysis:
-
name = "douban_spider": Defines the spider’s name. -
start_urls: Defines the initial URL where the spider starts crawling (Douban Movie Top 250 page). -
parseMethod:-
Uses CSS selectors to extract the title, rating, and quote of each movie.
-
span.title::text: Extracts the movie title. -
span.rating_num::text: Extracts the movie rating. -
span.inq::text: Extracts the movie quote.
-
-
Pagination Handling:
-
Uses
span.next a::attr(href)to extract the link to the next page. -
If a next page exists, uses
response.followto continue crawling.
-
Run the following command in the command line to start the spider:
This will start the spider and save the extracted data to the douban_movies.csv file.

Note: The above content is for learning purposes only. When scraping data, please comply with the target website’s robots.txt file regulations.
Common Methods
Section titled “Common Methods”1. Spider Methods
Section titled “1. Spider Methods”| Method Name | Description | Example |
|---|---|---|
start_requests() |
Generate initial requests. Can customize request headers, methods, etc. | yield scrapy.Request(url, callback=self.parse) |
parse(response) |
Process the response and extract data. The core method of the 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 is closed, used for cleaning up resources or logging. | def closed(self, reason): print('Spider closed:', reason) |
log(message) |
Log a message. | self.log('This is a log message') |
2. Data Extraction Methods
Section titled “2. Data Extraction Methods”| Method Name | Description | Example |
|---|---|---|
response.css(selector) |
Extract data using CSS selectors. | title = response.css('h1::text').get() |
response.xpath(selector) |
Extract data using XPath selectors. | title = response.xpath('//h1/text()').get() |
get() |
Extract the first matching result from SelectorList (string). |
title = response.css('h1::text').get() |
getall() |
Extract all matching results from SelectorList (list). |
titles = response.css('h1::text').getall() |
attrib |
Extract the attribute of the current node. | link = response.css('a::attr(href)').get() |
3. Request and Response Methods
Section titled “3. Request and Response Methods”| Method Name | 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 status code of the response. | if response.status == 200: print('Success') |
response.meta |
Get additional data passed in the request. | value = response.meta.get('key') |
response.headers |
Get the header information of the response. | content_type = response.headers.get('Content-Type') |
4. Middleware and Pipeline Methods
Section titled “4. Middleware and Pipeline Methods”| Method Name | 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 is returned (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 is closed (pipeline). | def close_spider(self, spider): self.file.close() |
5. Tools and Extension Methods
Section titled “5. Tools and Extension Methods”| Method Name | Description | Example |
|---|---|---|
scrapy shell |
Launch an interactive shell for debugging and testing selectors. | scrapy shell 'http://example.com' |
scrapy crawl <spider_name> |
Run the 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 the specified URL. | scrapy fetch 'http://example.com' |
scrapy view |
View the page downloaded by Scrapy in a browser. | scrapy view 'http://example.com' |
6. Common Settings (settings.py)
Section titled “6. Common Settings (settings.py)”| Setting Item | Description | Example |
|---|---|---|
USER_AGENT |
Set the User-Agent in the request header. | USER_AGENT = 'Mozilla/5.0' |
ROBOTSTXT_OBEY |
Whether to comply with robots.txt rules. |
ROBOTSTXT_OBEY = False |
DOWNLOAD_DELAY |
Set download delay to avoid excessively fast requests. | 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 automatic throttling extension. | AUTOTHROTTLE_ENABLED = True |
7. Other Common Methods
Section titled “7. Other Common Methods”| Method Name | 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 format. | data = response.json() |
response.text |
Get the text content of the response. | html = response.text |
response.selector |
Get the Selector object of the response content. |
title = response.selector.css('h1::text').get() |
The above tables list the commonly used methods in Scrapy and their functions. These methods cover various aspects of spider development, including request generation, data extraction, middleware processing, pipeline operations, etc. By mastering these methods, you can efficiently write and manage Scrapy spiders. If you need more detailed features, refer to the Scrapy Official Documentation.
Method Usage Examples
Section titled “Method Usage Examples”1. start_requests()
Section titled “1. start_requests()”The start_requests() method is the entry point of a Scrapy spider, used to generate initial requests. Typically, the spider’s starting URLs are defined in this method.
Example
Section titled “Example”2. parse()
Section titled “2. parse()”The parse() method is the default response processing method, used to parse the response and extract data or generate new requests.
Example
Section titled “Example”3. parse_item()
Section titled “3. parse_item()”The parse_item() method is used to parse the response of a single item, typically used to extract structured data.
Example
Section titled “Example”4. follow()
Section titled “4. follow()”The follow() method is used to generate new requests and automatically process the response, typically used for following links.
Example
Section titled “Example”5. yield
Section titled “5. yield”The yield keyword is used to generate requests or items and pass them to the Scrapy engine for processing.
Example
Section titled “Example”6. Item
Section titled “6. Item”The Item class is used to define data structures, typically used to store data extracted from web pages.
Example
Section titled “Example”7. ItemLoader
Section titled “7. ItemLoader”The ItemLoader class is used to load and populate Item objects, simplifying the data extraction and processing workflow.
Example
Section titled “Example”8. Request
Section titled “8. Request”The Request class is used to generate HTTP request objects, typically used to define the request’s URL, callback method, etc.
Example
Section titled “Example”9. Response
Section titled “9. Response”The Response class represents an HTTP response object, containing HTML content, status code, and other information returned from the server.
Example
Section titled “Example”10. Selector
Section titled “10. Selector”The Selector class is used to extract data from HTML or XML documents, supporting XPath and CSS selectors.
Example
Section titled “Example”11. CrawlSpider
Section titled “11. CrawlSpider”CrawlSpider is a special Spider class used to handle complex crawling rules and link following.
Example
Section titled “Example”12. LinkExtractor
Section titled “12. LinkExtractor”The LinkExtractor class is used to extract links from responses, typically used for automatically following links on a page.
Example
Section titled “Example”13. Pipeline
Section titled “13. Pipeline”The Pipeline class is used to process scraped data, typically used for data cleaning, storage, and other operations.
Example
Section titled “Example”14. Middleware
Section titled “14. Middleware”The Middleware class is used to process requests and responses, typically used for modifying request headers, handling exceptions, and other operations.