Python Web Crawle Pt.8 - Scrapy
Scrapy at a glance
1 | $ systeminfo | findstr /B /C:"OS 名称" /C:"OS 版本" |
Scrapy is an application framework for crawling web sites and extracting structured data which can be used for a wide range of useful applications, like data mining, information processing or historical archival.
In order to show you what Scrapy brings to the table, we’ll walk you through an example of a Scrapy Spider using the simplest way to run a spider.
Here’s the code for a spider that scrapes famous quotes from website http://quotes.toscrape.com, following the pagination:
1 | <div class="quote" itemscope="" itemtype="http://schema.org/CreativeWork"> |
1 | import scrapy |
Put this in a text file, name it to something like quotes_spider.py and run the spider using the runspider command:
1 | scrapy runspider quotes_spider.py -o quotes.json |
When this finishes you will have in the quotes.json file a list of the quotes in JSON format, containing text and author, looking like this (reformatted here for better readability):
That will generate an quotes.json file containing all scraped items, serialized in JSON.
1 | [ |
For historic reasons, Scrapy appends to a given file instead of overwriting its contents. If you run this command twice without removing the file before the second time, you’ll end up with a broken JSON file.
You can also use other formats, like JSON Lines:
1 | scrapy crawl quotes -o quotes.jl |
The JSON Lines format is useful because it’s stream-like, you can easily append new records to it. It doesn’t have the same problem of JSON when you run twice. Also, as each record is a separate line, you can process big files without having to fit everything in memory, there are tools like JQ to help doing that at the command-line.
Things that are good to know
Scrapy is written in pure Python and depends on a few key Python packages (among others):
- lxml, an efficient XML and HTML parser
- parsel, an HTML/XML data extraction library written on top of lxml,
- w3lib, a multi-purpose helper for dealing with URLs and web page encodings
- twisted, an asynchronous networking framework
- cryptography and pyOpenSSL, to deal with various network-level security needs
Scrapy Tutorial
Creating 1st project
Before you start scraping, you will have to set up a new Scrapy project.
Enter a directory where you’d like to store your code and run:
1 | scrapy startproject rebirth |
This will create a rebirth directory with the following contents:
1 | $ cd rebirth |
Our 1st Spider
Spiders are classes that you define and that Scrapy uses to scrape information from a website (or a group of websites). They must subclass scrapy.Spider and define the initial requests to make, optionally how to follow links in the pages, and how to parse the downloaded page content to extract data.
1 | # rebirth/spiders |
As you can see, our Spider subclasses scrapy.Spider and defines some attributes and methods:
-
name: identifies the Spider. It must be unique within a project, that is, you can’t set the same name for different Spiders. -
start_requests(): must return an iterable of Requests (you can return a list of requests or write a generator function) which the Spider will begin to crawl from. Subsequent requests will be generated successively from these initial requests. -
parse(): a method that will be called to handle the response downloaded for each of the requests made. The response parameter is an instance ofTextResponsethat holds the page content and has further helpful methods to handle it.The
parse()method usually parses the response, extracting the scraped data as dicts and also finding new URLs to follow and creating new requests (Request) from them.
Run the spider using scrapy crawl quotes,this command runs the spider with name quotes that we’ve just added, that will send some requests for the quotes.toscrape.com domain. You will get a file tree similar to this:
1 | G:. |
Instead of implementing a start_requests() method that generates scrapy.Request objects from URLs, you can just define a start_urls class attribute with a list of URLs. This list will then be used by the default implementation of start_requests() to create the initial requests for your spider:
1 | import scrapy |
The parse() method will be called to handle each of the requests for those URLs, even though we haven’t explicitly told Scrapy to do so. This happens because parse() is Scrapy’s default callback method, which is called for requests without an explicitly assigned callback.
Extracting data
The best way to learn how to extract data with Scrapy is trying selectors using the shell Scrapy shell. Run:
1 | scrapy shell "http://quotes.toscrape.com/page/1/" # For Win |
You will get:
1 | [s] Available Scrapy objects: |
Using the shell, you can try selecting elements using CSS with the response object:
1 | In [1]: response.css('title') |
As an alternative, you could’ve written:
1 | In [5]: response.css('title::text')[0].extract() |
Using .extract_first() avoids an IndexError and returns None when it doesn’t find any element matching the selection.
You can also use the re()method to extract using regular expressions:
1 | In [7]: response.css('title::text').re(r'Quotes.*') |
1 | for quote in response.css("div.quote"): |
You can also use the xpath method to extract using regular expressions:
Each quote in http://quotes.toscrape.com is represented by HTML elements that look like this:
Emmet:
1 | div.quote>span.text{"The world as we have created it is a process of our thinking. It cannot be changed without changing our thinking."}+(span{by}>small.author+a[href="#"]{(about)})+div.tags{Tags:}>a.tag[href="#"]{$$$}*4 |
1 | <div class="quote"> |
1 | In [10]: response.xpath('//div[@class="quote"]//small/text()').extract_first() |
Following links
Let’s say, instead of just scraping the stuff from the first two pages from http://quotes.toscrape.com, you want quotes from all the pages in the website.
For that, Scrapy supports a CSS extension that let’s you select the attribute contents, like this:
1 | In [13]: response.css('li.next a::attr(href)').extract_first() |
Let’s see now our spider modified to recursively follow the link to the next page, extracting data from it:
1 | import scrapy |
As a shortcut for creating Request objects you can use response.follow:
1 | next_page = response.css('li.next a::attr(href)').extract_first() |
Unlike scrapy.Request, response.follow supports relative URLs directly - no need to call urljoin. Note that response.follow just returns a Request instance; you still have to yield this Request.
You can also pass a selector to response.follow instead of a string; this selector should extract necessary attributes:
1 | for href in response.css('li.next a::attr(href)'): |
For <a> elements there is a shortcut: response.follow uses their href attribute automatically. So the code can be shortened further:
1 | for a in response.css('li.next a'): |
More simplicity:
1 | response.follow(response.css('li.next a')[0],callback=self.parse) |
In this example, it creates a sort of loop, following all the links to the next page until it doesn’t find one – handy for crawling blogs, forums and other sites with pagination.
Scraping author information
1 | import scrapy |
scrapy crawl author -o author.json:
1 | [ |
The interesting thing this spider demonstrates is that, even if there are many quotes from the same author, we don’t need to worry about visiting the same author page multiple times. By default, Scrapy filters out duplicated requests to URLs already visited, avoiding the problem of hitting servers too much because of a programming mistake. This can be configured by the settingDUPEFILTER_CLASS.
Using spider arguments
You can provide command line arguments to your spiders by using the -a option when running them:
1 | scrapy crawl quotes -o quotes-humor.json -a tag=humor |
These arguments are passed to the Spider’s __init__ method and become spider attributes by default.
In this example, the value provided for the tag argument will be available via self.tag. You can use this to make your spider fetch only quotes with a specific tag, building the URL based on the argument:
1 | import scrapy |
If you pass the tag=humor argument to this spider, you’ll notice that it will only visit URLs from the humor tag, such as http://quotes.toscrape.com/tag/humor.
1 | [{"text": "\u201cThe world as we have created it is a process of our thinking. It cannot be changed without changing our thinking.\u201d", "author": "Albert Einstein"}, |
By now, we have two spiders:
1 | scrapy list |
Command line tool
Scrapy is controlled through the scrapy command-line tool, to be referred here as the “Scrapy tool” to differentiate it from the sub-commands, which we just call “commands” or “Scrapy commands”.
Configuration settings
Scrapy will look for configuration parameters in ini-style scrapy.cfg files in standard locations:
/etc/scrapy.cfgorc:\scrapy\scrapy.cfg(system-wide),~/.config/scrapy.cfg($XDG_CONFIG_HOME) and~/.scrapy.cfg($HOME) for global (user-wide) settings, andscrapy.cfginside a scrapy project’s root
Settings from these files are merged in the listed order of preference: user-defined values have higher priority than system-wide defaults and project-wide settings will override all others, when defined.
Available tool commands
startproject
- Syntax:
scrapy startproject <project_name> [project_dir]
Creates a new Scrapy project named project_name, under the project_dir directory. If project_dirwasn’t specified, project_dir will be the same as project_name.
Usage example:
1 | $ scrapy startproject myproject |
genspider
- Syntax:
scrapy genspider [-t template] <name> <domain>
Create a new spider in the current folder or in the current project’s spiders folder, if called from inside a project. The <name> parameter is set as the spider’s name, while <domain> is used to generate the allowed_domains and start_urls spider’s attributes.
Usage example:
1 | $ scrapy genspider -l |
This is just a convenience shortcut command for creating spiders based on pre-defined templates, but certainly not the only way to create spiders. You can just create the spider source code files yourself, instead of using this command.
crawl
- Syntax:
scrapy crawl <spider> - Requires project: yes
Start crawling using a spider.
Usage examples:
1 | $ scrapy crawl myspider |
check
- Syntax:
scrapy check [-l] <spider> - Requires project: yes
Run contract checks.
Usage examples:
1 | $ scrapy check -l |
list
- Syntax:
scrapy list - Requires project: yes
List all available spiders in the current project. The output is one spider per line.
Usage example:
1 | $ scrapy list |
fetch
- Syntax:
scrapy fetch <url> - Requires project: no
Downloads the given URL using the Scrapy downloader and writes the contents to standard output.
The interesting thing about this command is that it fetches the page how the spider would download it. For example, if the spider has a USER_AGENT attribute which overrides the User Agent, it will use that one.
So this command can be used to “see” how your spider would fetch a certain page.
Supported options:
--spider=SPIDER: bypass spider autodetection and force use of specific spider--headers: print the response’s HTTP headers instead of the response’s body--no-redirect: do not follow HTTP 3xx redirects (default is to follow them)
Usage examples:
1 | $ scrapy fetch --nolog http://www.example.com/some/page.html |
view
- Syntax:
scrapy view <url> - Requires project: no
Opens the given URL in a browser, as your Scrapy spider would “see” it. Sometimes spiders see pages differently from regular users, so this can be used to check what the spider “sees” and confirm it’s what you expect.
Supported options:
--spider=SPIDER: bypass spider autodetection and force use of specific spider--no-redirect: do not follow HTTP 3xx redirects (default is to follow them)
Usage example:
1 | $ scrapy view http://www.example.com/some/page.html |
shell
- Syntax:
scrapy shell [url] - Requires project: no
Starts the Scrapy shell for the given URL (if given) or empty if no URL is given. Also supports UNIX-style local file paths, either relative with ./ or ../ prefixes or absolute file paths.
Supported options:
--spider=SPIDER: bypass spider autodetection and force use of specific spider-c code: evaluate the code in the shell, print the result and exit--no-redirect: do not follow HTTP 3xx redirects (default is to follow them); this only affects the URL you may pass as argument on the command line; once you are inside the shell,fetch(url)will still follow HTTP redirects by default.
Usage example:
1 | $ scrapy shell http://www.example.com/some/page.html |
parse
- Syntax:
scrapy parse <url> [options] - Requires project: yes
Fetches the given URL and parses it with the spider that handles it, using the method passed with the --callback option, or parse if not given.
Supported options:
--spider=SPIDER: bypass spider autodetection and force use of specific spider--a NAME=VALUE: set spider argument (may be repeated)--callbackor-c: spider method to use as callback for parsing the response--metaor-m: additional request meta that will be passed to the callback request. This must be a valid json string. Example: –meta=’{“foo” : “bar”}’--pipelines: process items through pipelines--rulesor-r: useCrawlSpiderrules to discover the callback (i.e. spider method) to use for parsing the response--noitems: don’t show scraped items--nolinks: don’t show extracted links--nocolour: avoid using pygments to colorize the output--depthor-d: depth level for which the requests should be followed recursively (default: 1)--verboseor-v: display information for each depth level
Usage example:
1 | $ scrapy parse http://www.example.com/ -c parse_item |
settings
- Syntax:
scrapy settings [options] - Requires project: no
Get the value of a Scrapy setting.
If used inside a project it’ll show the project setting value, otherwise it’ll show the default Scrapy value for that setting.
Example usage:
1 | $ scrapy settings --get BOT_NAME |
runspider
- Syntax:
scrapy runspider <spider_file.py> - Requires project: no
Run a spider self-contained in a Python file, without having to create a project.
Example usage:
1 | $ scrapy runspider myspider.py |
version
- Syntax:
scrapy version [-v] - Requires project: no
Prints the Scrapy version. If used with -v it also prints Python, Twisted and Platform info, which is useful for bug reports.



