从这篇文章开始,我将利用三篇文章分别讲解 Scrapy 爬虫模板。 Scrapy 爬虫模板包含四个模板:
这篇文章我先来讲解一下 CrawlSpider 模板。
CrawlSpider 是常用的 Spider ,通过定制规则来跟进链接。对于大部分网站我们可以通过修改规则来完成爬取任务。 CrawlSpider 常用属性是 rules* ,它是一个或多个 Rule 对象以 tuple 的形式展现。其中每个 Rule 对象定义了爬取目标网站的行为。
Tip:如果有多个 Rule 对象命中同一个链接,那么只有第一个 Rule 对象生效。
我们来看一下 Role 的语法:
Rule(link_extractor [,callback = None] [,cb_kwargs = None] [,follow = None] [,process_links = None] [,process_request = None])
参数解析:
这个案例我们爬取的是名人名言网站,我们需要做的是提取名言内容、作者姓名和标签,然后通过作者链接进入到作者介绍的页面,最后我们爬取的作者的详细信息。
import scrapy
from scrapy.spiders import CrawlSpider, Rule
from scrapy.linkextractors import LinkExtractor
class Quotes(CrawlSpider):
name = "quotes"
allow_domain = ['quotes.toscrape.com']
start_urls = ['http://quotes.toscrape.com']
rules = (
Rule(LinkExtractor(allow='/page/\d+'), callback='parse_quotes', follow=True),
Rule(LinkExtractor(allow='/author/\w+_'), callback='parse_author')
)
def parse_quotes(self, response):
for quote in response.css('.quote'):
yield {
'content': quote.css('.text::text').extract_first(),
'author': quote.css('.author::text').extract_first(),
'tags': quote.css('.tag::text').extract()
}
def parse_author(self, response):
name = response.css('.author-title::text').extract_first()
author_born_date = response.css('.author_born_date::text').extract_first()
author_description = response.css('.author_description::text').extract_first()
return ({
'name': name,
'author_born_date': author_born_date,
'author_description': author_description
})
import scrapy
from scrapy.spiders import CrawlSpider, Rule
from scrapy.linkextractors import LinkExtractor
class Quotes(CrawlSpider):
name = "quotes"
allow_domain = ['quotes.toscrape.com']
start_urls = ['http://quotes.toscrape.com']
rules = (
Rule(LinkExtractor(allow='/page/\d+'), callback='parse_quotes', follow=True),
Rule(LinkExtractor(allow='/author/\w+_'), callback='parse_author')
)
def parse_quotes(self, response):
for quote in response.css('.quote'):
yield {
'content': quote.css('.text::text').extract_first(),
'author': quote.css('.author::text').extract_first(),
'tags': quote.css('.tag::text').extract()
}
def parse_author(self, response):
name = response.css('.author-title::text').extract_first()
author_born_date = response.css('.author_born_date::text').extract_first()
author_description = response.css('.author_description::text').extract_first()
return ({
'name': name,
'author_born_date': author_born_date,
'author_description': author_description
})
上述代码中 Rule(LinkExtractor(allow='/page/\d+'), callback='parse_quotes', follow=True),
代码段定义了爬取所有名人名言页的规则,即只要符合 /page/\d+
的所有链接就被视为名人名言页,然后我们调用 parse_quotes 方法提取相关数据。 在 Rule(LinkExtractor(allow='/author/\w+_'), callback='parse_author')
代码段中我们定义了爬取作者信息页的规则,即只要符合 /author/\w+_
的所有链接就被视为作者信息页,之后我们调用 parse_author 方法提取相关数据。
)代码段中我们定义了爬取作者信息页的规则,即只要符合
/author/\w+_```的所有链接就被视为作者信息页,之后我们调用 parse_author 方法提取相关数据。