使用CrawlSpider可以自动提取网页中的链接,生成请求

1 生成CrawlSpider蜘蛛文件

crapy genspider -t crawl 蜘蛛文件名称 url

2 导入的模块

from scrapy.linkextractors import LinkExtractor  # 专门提取页面链接from scrapy.spiders import CrawlSpider, Rule  # 处理链接请求

3 定义提取链接规则

#  提取链接规则rules = (    # follow : 是否跟进页面 根据规则 进行再次提取链接    Rule(LinkExtractor(allow=(r'position_detail',)), callback='parse_item', follow=False,process_links='pro_link'),    Rule(LinkExtractor(allow=(r'start=\d+',)), follow=True),)

LinkExtractor() #提取页面的链接,返回列表形式

    没有参数默认提取全部链接

    参数allow为提取规则

Rule() #处理链接请求

    参数1:LinkExtractor实例

    参数callback:指定处理返回的响应的函数

    参数follow:是否对返回的响应里的链接再次跟进提取,默认为True

    参数process_links:指定函数对提取的链接做再次处理,指定的函数的参数格式为(self,links),函数需要有返回链接links,

rules中可以写多个Rule()

注意:蜘蛛文件不要重写parse函数,以及使用parse作为回调函数,因为CrawlSpider使用了parse方法实现其逻辑