動態

詳情 返回 返回

Python爬蟲進階:使用Scrapy庫進行數據提取和處理 - 動態 詳情

在我們的初級教程中,我們介紹瞭如何使用Scrapy創建和運行一個簡單的爬蟲。在這篇文章中,我們將深入瞭解Scrapy的強大功能,學習如何使用Scrapy提取和處理數據。

一、數據提取:Selectors和Item

在Scrapy中,提取數據主要通過Selectors來完成。Selectors基於XPath或CSS表達式的查詢語言來選取HTML文檔中的元素。你可以在你的爬蟲中使用response對象的xpathcss方法來創建一個Selector對象。

例如,我們可以修改我們的QuotesSpider爬蟲,使用Selectors來提取每個引用的文本和作者:

import scrapy

class QuotesSpider(scrapy.Spider):
    name = "quotes"

    start_urls = [
        'http://quotes.toscrape.com/page/1/',
    ]

    def parse(self, response):
        for quote in response.css('div.quote'):
            text = quote.css('span.text::text').get()
            author = quote.css('span small::text').get()
            print(f'Text: {text}, Author: {author}')

此外,Scrapy還提供了Item類,可以定義你想要收集的數據結構。Item類非常適合收集結構化數據,如我們從quotes.toscrape.com中獲取的引用:

import scrapy

class QuoteItem(scrapy.Item):
    text = scrapy.Field()
    author = scrapy.Field()

然後我們可以修改QuotesSpider爬蟲,使其生成和收集QuoteItem對象:

class QuotesSpider(scrapy.Spider):
    name = "quotes"

    start_urls = [
        'http://quotes.toscrape.com/page/1/',
    ]

    def parse(self, response):
        for quote in response.css('div.quote'):
            item = QuoteItem()
            item['text'] = quote.css('span.text::text').get()
            item['author'] = quote.css('span small::text').get()
            yield item

二、數據處理:Pipelines

Scrapy使用數據管道(pipelines)來處理爬蟲從網頁中抓取的Item。當爬蟲生成一個Item,它將被髮送到Item Pipeline進行處理。

Item Pipeline是一些按照執行順序排列的類,每個類都是一個數據處理單元。每個Item Pipeline組件都是一個Python類,必須實現一個process_item方法。這個方法必須返回一個Item對象,或者拋出DropItem異常,被丟棄的item將不會被之後的pipeline組件所處理。

例如,我們可以添加一個Pipeline,將收集的引用保存到JSON文件中:

import json

class JsonWriterPipeline(object):

    def open_spider(self, spider):
        self.file = open('quotes.jl', 'w')

    def close_spider(self, spider):
        self.file.close()

    def process_item(self, item, spider):
        line = json.dumps(dict(item)) + "\n"
        self.file.write(line)
        return item

然後你需要在項目的設置文件(settings.py)中啓用你的Pipeline:

ITEM_PIPELINES = {
   'tutorial.pipelines.JsonWriterPipeline': 1,
}

在這篇文章中,我們更深入地探討了Scrapy的功能,包括如何使用Selectors和Item提取數據,如何使用Pipelines處理數據。在下一篇文章中,我們將學習如何使用Scrapy處理更復雜的情況,如登錄、cookies、以及如何避免爬蟲被網站識別和封鎖等問題。

user avatar u_17400586 頭像 u_17353607 頭像 oeasy 頭像 u_17467352 頭像 xingchendahai_68d7dff410962 頭像 haoqidedalianmao 頭像 aitigou 頭像 gqkmiss 頭像 taoqix 頭像 hafen 頭像 aizuiyoujie 頭像 fengliudeshanghen 頭像
點贊 14 用戶, 點贊了這篇動態!
點贊

Add a new 評論

Some HTML is okay.