#-*-Coding:utf-8-*-import scrapy,refrom scrapy.linkextractors import linkextractorfrom scrapy.spiders import CrawlSpi Der, Rulefrom crawlspider.items import crawlspideritemclass crawlspidersspider (crawlspider): name = ' Crawlspiders ' A Llowed_domains = [' sbiquge.com '] start_urls = [' https://www.sbiquge.com/biqukan/'] rules = (Rule (linkextract or (allow= "/\d+?_\d+?/", unique=true), callback= ' Parse_item ', follow=false), # Note the use of Restricted_xpath to extract the link can only go to the label is good, Do not go to specific tag attributes, that is called superfluous. # This rule instance has the callback attribute, then it extracts the link from all the downloaded response and downloads the link content from the callback function to process the data) def parse_item (self, Response): Chap_list = Response.xpath ('.//*[@class = "Listmain"]/dl/dd ') for chapter in chap_list:novel_name = Chapter.xpath ( '//*[@id = ' book ']/div[1]/div/a[2]/text () '). Extract_first () Chapter_name = Chapter.xpath ('./a/text () '). Extract_fi RST () Chapter_link = Chapter.xpath ('./a/@href '). Extract_first () if Chapter_name:item= Crawlspideritem (chapter_title=chapter_name,novel_name=novel_name) url = response.urljoin (chapter_link) Request = Scrapy. Request (url=url,callback=self.parse_body) request.meta[' key ' = Item yield request def PA Rse_body (self,response): item = response.meta[' key '] content_list = Response.xpath ('.//*[@id = "Content"]. Re (' ([\u4e00-\u9fa5]|<br>) +? ') # Match to a list # use the RE to directly match the Chinese character content of the novel. The regular matches anything under the tag so we can extract the data we want CONTENT_STR = ". Join (Content_list) cont ent = re.sub (' <br><br> ', ' \ n ', content_str) # segment The matching chapters item[' content ' = content yield Item
The focus is on Crawlspider learning!!!!!!!!!!!!!
* * Through the previous study we can do some simple automatic word crawling, for some of the more rules of the site, we seem to be able to use the spider to cope with, but, for some more complex or linked to the storage of irregular sites how to crawl it, the next crawler is to solve the problem, It also allows for highly automated crawling of links and linked content * *
1
The Crawlspider class is another class that builds a crawler.
* (By the way, we can inherit four kinds to build our scrapy crawler, they are: Spider class, Crawlspider class, Csvfeedspider class and Xmlfeedspider class, What we're talking about today is a reptile built by the Crawlspider class.
1
The Crawlspider class uses rules to make crawling of links (Web pages) more versatile, in other words, crawlspider crawlers are generic crawlers, and spider crawlers are more like crawlers for some special sites.
Let's start with a formal explanation of the Crawlspider crawler ....
First we build a crawler project:
Scrapy Startproject Crawlspider
1
We're familiar with this, and then we create a crawlspider crawler.
Scrapy genspider-t Crawl Crawlspider domain.com
1
Notice above, we have more than one '-t crawl ' in the Spider Crawler, this is the class of value crawlers
So we can find this crawler in our spiders file.
Import Scrapy
From scrapy.linkextractors import Linkextractor
From scrapy.spiders import Crawlspider, Rule
Class Crawlspiderspider (Crawlspider):
name = ' Crawlspider '
Allowed_domains = [' domain.com ']
Start_urls = [' http://domain.com/']
Rules = (
Rule (Linkextractor (allow=r ' items/'), callback= ' Parse_item ', follow=true),
)
def parse_item (self, Response):
i = {}
#i [' domain_id '] = Response.xpath ('//input[@id = "Sid"]/@value '). Extract ()
#i [' name '] = Response.xpath ('//div[@id = "name"]). Extract ()
#i [' description '] = Response.xpath ('//div[@id = "description"]). Extract ()
return I
Above is to open the crawler, automatically generated a piece of code, this code can be said basically for the Crawlspider crawler structure has a construction, we see that there is a rules property, and this crawler inherits the class is Crawlspider, These two points are the difference from the previous spider spiders. Where the rules attribute makes the crawler's core
So we should talk about the Rules property before we start talking about our actual project.
The Rules property is made up of several rule objects, and the Rule object defines the regulations for operations such as extracting links
So what is the structure of rule?
The Rule object has six properties, respectively:
Linkextractor (...) to extract links from the response
callback= ' str ', callback function, used to extract data to populate item
Cb_kwargs, a dictionary of arguments passed to the callback function
Follow=true/false, do you need to follow up on the extracted links?
Process_links, a function for filtering links
Process_request, a function to filter the link request
The above parameters are optional except for linkextractor, and when the callback parameter is none, we call this rule a ' springboard ', which is to download only the page and not perform any behavior, usually as a paging function
We need to explain primarily the Linkextractor parameter and the follow parameter:
One, linkextractor parameters, is obviously used to extract the link. So how does he define the rules for extracting links? It has 10 parameters that define the rules for extracting links, respectively:
1. allow= ' re_str ': Regular expression string, extracting the link in response that conforms to the RE expression.
2. deny= ' Re_str ': Exclude links for regular expression matching
3. restrict_xpaths= ' Xpath_str ': extracting a link that satisfies an XPath expression
4. restrict_css= ' Css_str ': extracting links that satisfy CSS expressions
5. allow_domains= ' domain_str ': Allowed domain names
6. deny_domains= ' domain_str ': excluded domain names
7. tags= ' tag '/[' Tag1 ', ' Tag2 ',...] : Extracts the link under the specified label, which is extracted from the A and Area tabs by default
8. attrs=[' href ', ' src ',...] : Extracting a link that satisfies a property
9. Unique=true/false: Link whether to go heavy
10.process_value: Value processing function with precedence greater than allow
The above parameters can be used together to extract a link that satisfies the condition at the same time
Second, follow parameters:
is a Boolean value that is used to follow the processing of links, when callback is none, the default is a follow-up link, and the value is true; When callback is not empty, the default is false and no follow-up links. Of course, we can assign values as needed,
So, what is called follow-up, what do not follow?
Is the rule you defined earlier. The page that has been extracted to the link is not a fetch link at once.
1
2
Good! So how does the rules work?
Thus, the link to rule extraction automatically calls the parse function, returns the link's response, and then assigns the response to the callback callback function, populating the item with the parse of the callback function
By the way, Crawlspider Crawler also has a Parse_start_url () method, which is used to parse the link page in Start_urls, which is commonly used in crawlers with a springboard for parsing the home page.
Saying so much, let's talk about our reptile project. Crawling a whole station of fiction with Crawlspider crawlers.
Scrapy Advanced (Crawlspider crawler __ crawls the whole station novel)