天天看點

Python Scrapy 全站爬蟲

基本指令:

scrapy startproject test2  建立工程

scrapy genspider test www.abc.com    建立基于scrapy.Spider 的爬蟲  

scrapy genspider -t crawl test www.abc.com 建立基于CrawlSpider的爬蟲

scrapy  crawl test -o test.json 運作爬蟲test資料儲存到test.json中

抓取百度應用商店資訊代碼如下:

import scrapy
from scrapy.linkextractors import LinkExtractor
from scrapy.spiders import CrawlSpider, Rule


class test(CrawlSpider):
    name = 'test'
    allowed_domains = ['as.baidu.com']
    start_urls = [
               'https://as.baidu.com/',
               ]

    rules = (
        Rule(LinkExtractor(allow='https://as.baidu.com/software/',deny='https://as.baidu.com/software/\d+\.html'),  follow=True),
            
        Rule(LinkExtractor(allow='https://as.baidu.com/software/\d+\.html'), callback='parse_item', follow=True),
    )

    def parse_item(self, response):
        i = {}
        i['url']=response.url
        return i
           

全站爬蟲原理:

            1、先擷取start_urls中網頁内容A

            2、在獲得的網頁内容A中 比對rules位址

            3、擷取 比對的rules位址 的頁面内容B ,如果設定了callback 就調用回調函數,如果follow=True 就繼續在頁面内容B中比對rules位址并重複步驟3

注意:

rules中存在多條比對規則時 一個url滿足其中一條就不會繼續比對吓一跳了。如上面例子

如果如下面寫下法 就擷取不到資料

rules = (
        Rule(LinkExtractor(allow='https://as.baidu.com/software/'),  follow=True),
            
        Rule(LinkExtractor(allow='https://as.baidu.com/software/\d+\.html'), callback='parse_item', follow=True),
    )
           

但是換個位置就可以擷取到資料了

rules = (
      
        Rule(LinkExtractor(allow='https://as.baidu.com/software/',deny='https://as.baidu.com/software/\d+\.html'),  follow=True),
        Rule(LinkExtractor(allow='https://as.baidu.com/software/\d+\.html'), callback='parse_item', follow=True),

    )