scrapy.Spider的屬性和方法 屬性: name:spider的名稱,要求唯一 allowed_domains:允許的域名,限制爬蟲的范圍 start_urls:初始urls custom_settings:個性化設置,會覆蓋全局的設置 crawler:抓取器,spider將綁定到它上面 custom_settings:配置實例,包含工程中所有的配置變量 logger:日志實例,打印調試信息 方法: from_crawler(crawler, *args, **kwargs):類方法,用於創建spider start_requests():生成初始的requests make_requests_from_url(url):遍歷urls,生成一個個request parse(response):用來解析網頁內容 log(message[,level.component]):用來記錄日志,這里請使用logger屬性記錄日志,self.logger.info('visited success') closed(reason):當spider關閉時調用的方法 子類: 主要CrawlSpider 1:最常用的spider,用於抓取普通的網頁 2:增加了兩個成員 1)rules:定義了一些抓取規則--鏈接怎么跟蹤,使用哪一個parse函數解析此鏈接 2)parse_start_url(response):解析初始url的相應 實例: import scrapy from scrapy.spiders import CrawlSpider, Rule from scrapy.linkextractors import LinkExtractor class MySpider(CrawlSpider): name = 'example.com' allowed_domains = ['example.com'] start_urls = ['http://www.example.com'] rules = ( # Extract links matching 'category.php' (but not matching 'subsection.php') # and follow links from them (since no callback means follow=True by default). Rule(LinkExtractor(allow=('category\.php', ), deny=('subsection\.php', ))), # Extract links matching 'item.php' and parse them with the spider's method parse_item Rule(LinkExtractor(allow=('item\.php', )), callback='parse_item'), ) def parse_item(self, response): self.logger.info('Hi, this is an item page! %s', response.url) item = scrapy.Item() item['id'] = response.xpath('//td[@id="item_id"]/text()').re(r'ID: (\d+)') item['name'] = response.xpath('//td[@id="item_name"]/text()').extract() item['description'] = response.xpath('//td[@id="item_description"]/text()').extract() return item