DI logo and Scrapy logo

L’esigenza di velocizzare il web scraping e al tempo stesso evitare di attivare sistemi anti-bot richiede strumenti di scraping funzionali. Scrapy è uno dei più usati. Continua a leggere per scoprire perché merita la tua attenzione e come usarlo in modo efficace.

Che cos’è Scrapy e quali vantaggi ti offre?

Scrapy è un framework open-source per il web crawling in Python. È popolare per una buona ragione: i suoi vantaggi includono:

  • la capacità di gestire più richieste contemporaneamente, così il web scraping richiede meno tempo
  • nessuna necessità di manutenere il codice
  • adatto a progetti su larga scala
  • consente di personalizzare la gestione di richieste e risposte, ad esempio aggiungendo la rotazione dello user-agent, gestendo i tentativi e i proxy
  • funziona bene con siti web ricchi di JavaScript e offre funzionalità come il ritardo delle richieste e l’auto-throttling per evitare di sovraccaricare i server 
  • ha una pipeline degli elementi integrata, quindi puoi estrarre, archiviare e salvare dati in vari formati, come JSON, CSV e XML
  • include selettori CSS ed espressioni XPath, che ti consentono di estrarre con precisione gli elementi HTML necessari 

Per conoscere tutte le funzionalità di Scrapy, consulta la sua documentazione ufficiale. In questo articolo ci concentreremo su come usare Scrapy. Visiteremo il nostro blog ed estrarremo tutti i titoli degli articoli per mostrarti come funziona lo strumento. 

Poiché il web scraping comporta il rischio di blocchi, usare strumenti di crawling insieme ai proxy non è una novità. In questo tutorial ti mostreremo come installare e personalizzare Scrapy e come implementare i proxy. 

Preparazione 

Prima di iniziare, assicurati di avere tutti i programmi e gli strumenti necessari. Per questo tutorial ci servono: 

  • Visual Studio Code, o qualunque altro IDE che supporti Python 
  • Python, versione 3.10.0 nel nostro caso
  • pip, noi usiamo la versione 25.0.1

Puoi scaricare VS Code qui e installare Python dal suo sito ufficiale. Se non hai pip, incluso automaticamente in Python versione 3.4 e successive, apri il Notebook e salva questo codice in un file get-pip.py:


import urllib.request
import os
import sys

try:
    # download get-pip.py
    url = "https://bootstrap.pypa.io/get-pip.py"
    urllib.request.urlretrieve(url, "get-pip.py")

    # install pip
    os.system(f"{sys.executable} get-pip.py")
finally:
    # remove the script
    if os.path.exists("get-pip.py"):
        os.remove("get-pip.py")

      
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
      

Poi apri il prompt dei comandi e raggiungi la cartella in cui hai salvato il file:


cd path/to/your/file

      
        
      

Per esempio, abbiamo salvato un file nella cartella Documenti, quindi il comando sarà simile a cd/Documents.

Dopodiché, esegui il seguente comando:


python get-pip.py

      
        
      

Per verificare che pip funzioni correttamente, usa questo comando:


pip --version

      
        
      

Ora che hai tutto pronto, iniziamo.

Installare Scrapy e avviare un progetto

Per prima cosa, dobbiamo installare Scrapy. Per farlo, apri il prompt dei comandi, oppure il terminale di VS Code, ed esegui il seguente comando:


pip install Scrapy

      
        
      

Nota: se hai installato tutti gli strumenti necessari ma nel terminale di VS Code continua a comparire il messaggio “The term pip isn’t recognized as a name of cmdlet, function, script file, or operable program” oppure altri errori, prova a modificare le impostazioni di VS Code. Vai a Terminal>Integrated: Default Profile, puoi digitare terminal integrated nella barra di ricerca, cambia il profilo predefinito in prompt dei comandi e riavvia VS Code per attivare le nuove impostazioni.

Per avviare un progetto, raggiungi la cartella del progetto nel terminale di VS Code. Nel nostro caso, la cartella si chiama Project S e si trova nella cartella Documenti, quindi digitiamo cd Documents/Project S.

Poi digita questo comando:


scrapy startproject your_project_name

      
        
      

Assicurati di sostituire your_project_name con un nome effettivo. Per esempio, noi usiamo dataimpulse_blog.

Poi raggiungi la cartella del progetto:


cd your_project_name

      
        
      

Una volta lì, usa questo comando per creare uno spider:


scrapy genspider your_spider_name url_domain

      
        
      

Nel nostro caso, il comando è scrapy genspider blog_titles dataimpulse.com

Modificare il codice

Che tu apra la cartella del progetto in VS Code o tramite Esplora file, vedrai diversi file Python. Dobbiamo modificarli per estrarre i dati necessari.

Per prima cosa, nella cartella “spiders”, apri blog_titles.py e sostituisci il codice esistente con questo:


import scrapy


class BlogTitlesSpider(scrapy.Spider):
    name = 'blog_titles'
    allowed_domains = ['dataimpulse.com']
    start_urls = ['https://dataimpulse.com/blog/']
    def parse(self, response):
        self.logger.info(f"Visited {response.url}")

       
        titles = response.css('h3.blog-title a::text').getall()
        for title in titles:
            yield {'title': title.strip()}

       
        next_page = response.css('a.next::attr(href)').get()
        if next_page:
            yield response.follow(next_page, callback=self.parse)

      
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
      

Qui definisci la pagina da cui estrarre i dati e quelli che vuoi raccogliere, in questo caso i titoli. Modifichi anche il metodo parse.

Poi apri middlewares.py e incolla al suo interno il seguente blocco di codice:


# Define here the models for your spider middleware
#
# See documentation in:
# https://docs.scrapy.org/en/latest/topics/spider-middleware.html

from scrapy import signals

# useful for handling different item types with a single interface
from itemadapter import is_item, ItemAdapter


class BlogscraperSpiderMiddleware:
    # Not all methods need to be defined. If a method is not defined,
    # scrapy acts as if the spider middleware does not modify the
    # passed objects.

    @classmethod
    def from_crawler(cls, crawler):
        # This method is used by Scrapy to create your spiders.
        s = cls()
        crawler.signals.connect(s.spider_opened, signal=signals.spider_opened)
        return s

    def process_spider_input(self, response, spider):
        # Called for each response that goes through the spider
        # middleware and into the spider.

        # Should return None or raise an exception.
        return None

    def process_spider_output(self, response, result, spider):
        # Called with the results returned from the Spider, after
        # it has processed the response.

        # Must return an iterable of Request, or item objects.
        for i in result:
            yield i

    def process_spider_exception(self, response, exception, spider):
        # Called when a spider or process_spider_input() method
        # (from other spider middleware) raises an exception.

        # Should return either None or an iterable of Request or item objects.
        pass
    
    def process_start_requests(self, start_requests, spider):
        # Called with the start requests of the spider, and works
        # similarly to the process_spider_output() method, except
        # that it doesn’t have a response associated.

        # Must return only requests (not items).
        for r in start_requests:
            yield r

    def spider_opened(self, spider):
        spider.logger.info("Spider opened: %s" % spider.name)


class BlogscraperDownloaderMiddleware:
    # Not all methods need to be defined. If a method is not defined,
    # scrapy acts as if the downloader middleware does not modify the
    # passed objects.

    @classmethod
    def from_crawler(cls, crawler):
        # This method is used by Scrapy to create your spiders.
        s = cls()
        crawler.signals.connect(s.spider_opened, signal=signals.spider_opened)
        return s

    def process_request(self, request, spider):
        # Called for each request that goes through the downloader
        # middleware.

        # Must either:
        # - return None: continue processing this request
        # - or return a Response object
        # - or return a Request object
        # - or raise IgnoreRequest: process_exception() methods of
        #   installed downloader middleware will be called
        request.meta['proxy'] = spider.settings.get('http://login:password@hostname:port')

    def process_response(self, request, response, spider):
        # Called with the response returned from the downloader.

        # Must either;
        # - return a Response object
        # - return a Request object
        # - or raise IgnoreRequest
        return response

    def process_exception(self, request, exception, spider):
        # Called when a download handler or a process_request()
        # (from other downloader middleware) raises an exception.

        # Must either:
        # - return None: continue processing this exception
        # - return a Response object: stops process_exception() chain
        # - return a Request object: stops process_exception() chain
        pass

    def spider_opened(self, spider):
        spider.logger.info("Spider opened: %s" % spider.name)

      
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
      

Fai attenzione alla riga 81. Qui devi inserire le tue credenziali effettive nel formato http://login:password@hostname:port. Per ottenerle, vai al piano proxy necessario nel tuo dashboard DataImpulse. Non dimenticare di cambiare il formato del proxy nel pulsante in basso a destra. Se hai difficoltà, consulta pure la nostra guida alla gestione del tuo account DataImpulse.

Infine, vai a settings.py e assicurati che sia così:


# Scrapy settings for blogscraper project
#
# For simplicity, this file contains only settings considered important or
# commonly used. You can find more settings consulting the documentation:
#
#     https://docs.scrapy.org/en/latest/topics/settings.html
#     https://docs.scrapy.org/en/latest/topics/downloader-middleware.html
#     https://docs.scrapy.org/en/latest/topics/spider-middleware.html

BOT_NAME = "dataimpulse_blog"

SPIDER_MODULES = ["dataimpulse_blog.spiders"]
NEWSPIDER_MODULE = "dataimpulse_blog.spiders"


# Crawl responsibly by identifying yourself (and your website) on the user-agent
#USER_AGENT = "blogscraper (+http://www.yourdomain.com)"

# Obey robots.txt rules
ROBOTSTXT_OBEY = True

# Enable the downloader middlewares
DOWNLOADER_MIDDLEWARES = {
    'scrapy.downloadermiddlewares.httpproxy.HttpProxyMiddleware': 110,
    'scrapy.downloadermiddlewares.useragent.UserAgentMiddleware': None,
    'dataimpulse_blog.middlewares.BlogscraperSpiderMiddleware': 543,  # Add your ProxyMiddleware here
}

# Configure maximum concurrent requests performed by Scrapy (default: 16)
#CONCURRENT_REQUESTS = 32

# Configure a delay for requests for the same website (default: 0)
# See https://docs.scrapy.org/en/latest/topics/settings.html#download-delay
# See also autothrottle settings and docs
#DOWNLOAD_DELAY = 3
# The download delay setting will honor only one of:
#CONCURRENT_REQUESTS_PER_DOMAIN = 16
#CONCURRENT_REQUESTS_PER_IP = 16

# Disable cookies (enabled by default)
#COOKIES_ENABLED = False

# Disable Telnet Console (enabled by default)
#TELNETCONSOLE_ENABLED = False

# Override the default request headers:
#DEFAULT_REQUEST_HEADERS = {
#    "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",
#    "Accept-Language": "en",
#}

# Enable or disable spider middlewares
# See https://docs.scrapy.org/en/latest/topics/spider-middleware.html
#SPIDER_MIDDLEWARES = {
#    "blogscraper.middlewares.BlogscraperSpiderMiddleware": 543,
#}

# Enable or disable downloader middlewares
# See https://docs.scrapy.org/en/latest/topics/downloader-middleware.html
#DOWNLOADER_MIDDLEWARES = {
#    "blogscraper.middlewares.BlogscraperDownloaderMiddleware": 543,
#}

# Enable or disable extensions
# See https://docs.scrapy.org/en/latest/topics/extensions.html
#EXTENSIONS = {
#    "scrapy.extensions.telnet.TelnetConsole": None,
#}

# Configure item pipelines
# See https://docs.scrapy.org/en/latest/topics/item-pipeline.html
#ITEM_PIPELINES = {
#    "blogscraper.pipelines.BlogscraperPipeline": 300,
#}

# Enable and configure the AutoThrottle extension (disabled by default)
# See https://docs.scrapy.org/en/latest/topics/autothrottle.html
#AUTOTHROTTLE_ENABLED = True
# The initial download delay
#AUTOTHROTTLE_START_DELAY = 5
# The maximum download delay to be set in case of high latencies
#AUTOTHROTTLE_MAX_DELAY = 60
# The average number of requests Scrapy should be sending in parallel to
# each remote server
#AUTOTHROTTLE_TARGET_CONCURRENCY = 1.0
# Enable showing throttling stats for every response received:
#AUTOTHROTTLE_DEBUG = False

# Enable and configure HTTP caching (disabled by default)
# See https://docs.scrapy.org/en/latest/topics/downloader-middleware.html#httpcache-middleware-settings
#HTTPCACHE_ENABLED = True
#HTTPCACHE_EXPIRATION_SECS = 0
#HTTPCACHE_DIR = "httpcache"
#HTTPCACHE_IGNORE_HTTP_CODES = []
#HTTPCACHE_STORAGE = "scrapy.extensions.httpcache.FilesystemCacheStorage"

# Set settings whose default value is deprecated to a future-proof value
REQUEST_FINGERPRINTER_IMPLEMENTATION = "2.7"
TWISTED_REACTOR = "twisted.internet.asyncioreactor.AsyncioSelectorReactor"
FEED_EXPORT_ENCODING = "utf-8"

      
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
      

Qui abiliti il middleware e modifichi altri parametri, come cache, cookie, pipeline e così via.

Ora arriva il momento più importante. Apri il Terminale e digita cd per assicurarti di essere nella directory radice del progetto, dataimpulse_blog nel nostro caso. Cerca una cartella che contenga il file scrapy.cfg: è la directory radice. Quindi usa il seguente comando:


scrapy crawl blog_titles -o titles.json

      
        
      

Avvierà il tuo spider e salverà tutti i risultati in un file chiamato titles.json. Puoi controllare i risultati aprendo il file direttamente in VS Code. Ecco cosa abbiamo ottenuto:

Ora hai finito! Come vedi, Scrapy è facile da usare. Puoi modificare i dettagli necessari e sfruttare i proxy per ottenere i migliori risultati. Naturalmente, anche la scelta dei proxy è essenziale. DataImpulse offre residential proxy, datacenter e mobile ottenuti in modo legittimo, con un modello di prezzo pay-as-you-go. Hai IP in whitelist per esigenze universali senza esaurire il budget. Inizia con noi facendo clic sul pulsante “Prova ora” oppure scrivendoci a [email protected].