08. 脱缰的野马 crawlspider

基于crawlspider的全站数据爬取

  1.spider的子类

  2 .使用流程

    创建一个基于CrawlSpider的爬虫文件  scrapy genspider -t crawl spidername

import scrapy 
from scrapy.spider.crawl import CrawlSpider, Rule
fromm scrapy.linkextractors import LinkExtractor

class myspider(CrawlSpider):
    name = 'pra_crawlspider'
    start_urls = [ 'http://pic.netbian.com/ ]
    rules = [
         #实例化一个Rule ( 规则解析器 ) 的对象
         Rule(LinkExtractor(restrict_xpaths='//div[@class="page"]), callback="parse_item", follow=True)             
    ]
    
    def parse_item( self, response ) : 
        imgs = response.xpath( '//div[@class="slist"]//img )
        for  img in imgs:
            print(img.xpaht('./@src')).extract_first()
            print(img.xpath('./@alt')).extract_first()

  蜘蛛运行后,先访问start_url给定的第一个页面, 将响应对象res返回给parse方法, parse方法会根据rules指定的规则从res中提取url继续发送请求, 响应对象res会传递给callback指定的函数去处理.

猜你喜欢

转载自www.cnblogs.com/zhangjian0092/p/11704687.html