Introduction

Scrapy — An Overview

Scrapy is a comprehensive web scraping and crawling framework. It not only sends HTTP requests but also parses HTML documents and performs other tasks, combining functionalities of libraries like Requests and BeautifulSoup. Scrapy is highly extensible, allowing custom functionality additions. Beyond building web scrapers or crawlers, Scrapy simplifies deployment to the cloud, making it a versatile tool for data extraction and web automation projects. For more information, visit the Scrapy documentation.

Here's a guide on how to use Scrapy with ProxyPanel for web scraping:

We will scrape a simple quotes website using Scrapy and ProxyPanel proxies. We'll extract quotes from the website and save them into a JSON file.

Prerequisites

  • Install Python from the official website.

  • Install Scrapy using pip:

    pip install scrapy
  • In your dashboard, open My Proxies. If the proxy is still Pending, press Start proxy so it starts working.

    Take the host and the HTTP port from the "HTTP proxy" entry in the Connection column (the "SOCKS5 proxy" entry uses another port, which Scrapy won't need). Under Credentials, Copy username gives you the username; the password is masked until you press the eye button (Show / hide), and Copy password copies it. You don't need your account password.

    Set the four values as environment variables in the terminal you'll run Scrapy from:

    # macOS / Linux
    export PROXY_HOST="HOST"
    export PROXY_HTTP_PORT="HTTP_PORT"
    export PROXY_USERNAME="USERNAME"
    export PROXY_PASSWORD="PASSWORD"
    
    # Windows (PowerShell)
    $env:PROXY_HOST = "HOST"
    $env:PROXY_HTTP_PORT = "HTTP_PORT"
    $env:PROXY_USERNAME = "USERNAME"
    $env:PROXY_PASSWORD = "PASSWORD"
  • Create a file called quotes_spider.py and add the following code. Don't name it scrapy.py: a file with that name hides the Scrapy package from Python. The spider builds the proxy URL from your environment variables, so there is nothing to replace in it:

    import os
    from urllib.parse import quote as urlquote
    
    import scrapy
    
    # Proxy URL for the HTTP port; the login is percent-encoded so symbols can't break it
    PROXY = "http://{}:{}@{}:{}".format(
        urlquote(os.environ["PROXY_USERNAME"], safe=""),
        urlquote(os.environ["PROXY_PASSWORD"], safe=""),
        os.environ["PROXY_HOST"],
        os.environ["PROXY_HTTP_PORT"],
    )
    
    
    class QuotesSpider(scrapy.Spider):
        name = "quotes"
        start_urls = [
            "https://quotes.toscrape.com/tag/humor/",
        ]
    
        async def start(self):
            # Scrapy 2.13 and newer start the crawl here
            for request in self.start_requests():
                yield request
    
        def start_requests(self):
            # Older Scrapy versions call this method directly
            for url in self.start_urls:
                yield scrapy.Request(url, callback=self.parse, meta={"proxy": PROXY})
    
        def parse(self, response):
            for quote in response.css("div.quote"):
                yield {
                    "author": quote.xpath("span/small/text()").get(),
                    "text": quote.css("span.text::text").get(),
                }
    
            next_page = response.css('li.next a::attr("href")').get()
    
            if next_page is not None:
                yield response.follow(next_page, self.parse, meta={"proxy": PROXY})

    Scrapy's built-in HttpProxyMiddleware reads the proxy value of each request, decodes the username and password and sends them to the proxy in a Proxy-Authorization header. Recent Scrapy releases start a crawl from start() instead of start_requests(), which is why the spider defines both.

  • Run your script using this command:

    scrapy runspider quotes_spider.py -O quotes.json

    -O overwrites quotes.json on every run. The lowercase -o appends instead, and appending to a JSON file leaves it invalid.

  • Check the result in quotes.json. That's it! You have successfully scraped quotes using ProxyPanel proxy.