1. 程式人生 > 其它 >python爬蟲-CrawlSpider的全站資料爬取

python爬蟲-CrawlSpider的全站資料爬取

瞭解CrawlSpider

CrawlSpider是Spider的子類
它的建立方式是:

scrapy genspider -t crawl spiderName www.xxx.com

建立爬蟲檔案成功後,我們可以看到它和Spider最大的不同就是多了一個Rule

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

    rules = (
        Rule(LinkExtractor(allow=r'Items/'), callback='parse_item', follow=True),
    )

Rule:規則解析器
LinkExtractor:連結提取器
follow:能將新的請求網址也進行連結提取,以此來進行全站資料爬取。

連結提取器

根據指定規則提取連結
其中 allow='正則表示式' 來指定規則

規則解析器

將連結提取器提取到的連結進行指定規則的解析操作
其中 callback 來指定解析規則

使用CrawlSpider進行全站資料爬取

我們以 爬取w3school上所有技術的簡介 為例

觀察網頁

我們可以看見每一種技術都是在 /x.asp 連結下,所以這個就可以作為我們提取連結的規則


我們進入其中一個頁面,可以看見,技術的簡介位置。我們可以根據這個層級進行資料解析


編寫程式碼

"""
獲取w3school每個技術的簡介
"""

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


class TestSpider(CrawlSpider):
    name = 'test'
    # allowed_domains = ['www.xxx.com']
    start_urls = ['https://www.w3school.com.cn']

    rules = (
        Rule(LinkExtractor(allow=r'/[a-z].asp'), callback='parse_item', follow=False),
    )

    def parse_item(self, response):
        item = {}
        # item['domain_id'] = response.xpath('//input[@id="sid"]/@value').get()
        # item['name'] = response.xpath('//div[@id="name"]').get()
        # item['description'] = response.xpath('//div[@id="description"]').get()
        text_list = response.xpath('//*[@id="maincontent"]/div//text()').extract()
        text_list = ''.join(text_list)
        print(text_list)

既然我們能夠獲取簡介,那麼繼續編寫詳情頁的連結提取規則和資料解析方法,我們就能夠獲取更詳細的資料