在scrapy中提供了CrawlSpider来完成全站数据抓取.
-
创建项目
scrapy startproject qichezhijia
-
进入项目
cd qichezhijia
-
创建爬虫(CrawlSpider)
scrapy genspider
-t crawlershouche che168.com
和以往的爬虫不同. 该爬虫需要用到crawl的模板来创建爬虫.
-
修改spider中的rules和回调函数
class ErshoucheSpider(CrawlSpider): name = 'ershouche' allowed_domains = ['che168.com', 'autohome.com.cn'] start_urls = ['https://www.che168.com/beijing/a0_0msdgscncgpi1ltocsp1exx0/'] le = LinkExtractor(restrict_xpaths=("//ul[@class='viewlist_ul']/li/a",), deny_domains=("topicm.che168.com",) ) le1 = LinkExtractor(restrict_xpaths=("//div[@id='listpagination']/a",)) rules = ( Rule(le1, follow=True), # 单纯为了做分页 Rule(le, callback='parse_item', follow=False), # 单纯提取数据 ) def parse_item(self, response): print(response.url)
CrawlSpider的工作流程.
前期和普通的spider是一致的. 在第一次请求回来之后. 会自动的将返回的response按照rules中订制的规则来提取链接. 并进一步执行callback中的回调. 如果follow是True, 则继续在响应的内容中继续使用该规则提取链接. 相当于在parse中的scrapy.request(xxx, callback=self.parse)