Step 1:
Create a scrapy Project
Scrapy startproject test_project.
After the command is executed, the test_project directory is automatically generated, which contains files and directories such as items. py, pipelines. py, and spiders.
Step 2:
Define the items you are interested in items. py, such as title, URL, contact, and price. You can derive your own productitem from the system's built-in Item class. You can also create a new item from the custom item, or load an existing item through xpathitemloader, and add attributes (similar to the data table attribute design of the database ).
Definition method: Title = field (). Other attributes are similar
Step 3:
Customize 1 Spider (set how to crawl and parse ):
- A) derived from the base class basespider
- B) set the spider name (unique)
- C) Set start_urls: Set the seed URL (set allowed_domains & deny_domains, etc)
- D) overload the parse function: returns one request or item. The parse function declaration is as follows: def parse (self, response ):
- E) spider operating mechanism:
- I. Call the start_requests () function to generate a request for the seed URL, and set parse as the default callback function to process response.
- II. The callback function parse mainly performs two operations: 1) Parse to generate items; 2) generate a new request based on the parsing result;
- III. In the parsing process, selectors are mainly called for processing. Generally, built-in htmlxpathselector is used for processing.
- Iv. parsing the generated items is forwarded by the engine to the item pipeline Storage