Open In App

Scrapy – Spiders

Scrapy is a free and open-source web-crawling framework which is written purely in python. Thus, scrapy can be installed and imported like any other python package. The name of the package is self-explanatory. It is derived from the word ‘scraping’ which literally means extracting desired substance out of anything physically using a sharp tool. Scraping in web technology refers to an automated process in which bots called spiders are used to extract useful content and data from websites. 

Python scrapy package

This package is maintained and managed by an organization called Scrapinghub Ltd. This package comes with handy command line tools which makes project management an easy task.



The major use cases of this package are as follows:-

Features of scrapy

Web spider

Web spiders are called by technocrats using different names. The other names of web spider are web crawler, automatic indexer, crawler or simply spider. So don’t get confused with all these fancy names since they all refer to the same thing. A web spider is actually a bot that is programmed for crawling websites. 



The primary duty of a web spider is to generate indices for websites and these indices can be accessed by other software. For instance, the indices generated by a spider could be used by another party to assign ranks for websites. 

Steps to create a basic web spider 

To understand the basics of a  web spider in programming terminology, let’s build our own spider in python using scrapy. 

Step 1: Create a virtual environment

When you install scrapy in your system, it may conflict with other processes that are running. There are chances of getting errors and possible crashes while trying to use scrapy within a system. Although this step is not mandatory, I strongly recommend you to install scrapy in a virtual environment. 

A virtual environment provides an isolated container for your scrapy project which will not interfere with your actual system, thus preventing possible conflicts. I also suggest you to use pycharm as it creates a virtual environment for you automatically every time you create a new project. 

Step 2: Install python scrapy package

We can easily install the package from the terminal using Preferred Installer Program (PIP). Here I’m installing the package in the project that I have created- ‘first_spider’ Execute the following command in the command line interface you use. 

(venv) PS C:\Users\Kresh\PycharmProjects\first_spider> pip install scrapy

This will install the package along with all of it’s dependencies such as w3lib and lxml. 

Note: The installed package could only be accessed from the virtual environment in which you have installed the package. 

Step 3: Start a new scrapy project 

Scrapy has a resourceful command line utility. To know about various commands available in scrapy, type the following command in the terminal

(venv) PS C:\Users\Kresh\PycharmProjects\first_spider> scrapy

To know about the options available for  a specific command, type the following command.

(venv) PS C:\Users\Kresh\PycharmProjects\first_spider> scrapy <command_name> -h 

Enter the below command to start a scrapy project using the scrapy command-line utility

(venv) PS C:\Users\Kresh\PycharmProjects\first_spider> scrapy startproject <project_name>

Note: commands inside angular brackets ‘<>’ need to be replaced by your own data. 

Your project will now be created with a built-in tree structure of directories. 

Step 4: Create the spider

In the tree structure that has been created automatically, you can find  a directory called ‘spiders’. You should create all your spiders inside this directory only. 

Right click the directory - 'spider' --> new --> python file

Follow the above steps to create a new spider. It can be given any name of your choice but it must be a python file (.py). In our case, the name of the spider is ‘gfg_spider1’

spider created with the name – ‘gfg_spider1.py’

Now  you can start constructing the code. 

Now that you have learned where to type your source code for a spider. It is now time to create some spiders and see what they can do. The below examples will help you in getting a foundational knowledge about spiders.

Example1: Extracting HTML content of a webpage




# Spider dedicated to GeekForGeeks
  
# Importing necessary packages
import scrapy
  
# Creating the spider class
  
  
class GFGSpider (scrapy.Spider):
    # Assigning a name to the created spider
    name = "gfg"
  
    # Defining start_requests() function
    def start_requests(self):
        url_list = [""]     # Enter your target URL here
        for url in url_list:
            yield scrapy.Request(url=url, callback=self.parse)
  
    # Defining parse() function
    def parse(self, response):
        page = response.url.split("/")[-2]
        file_name = "gfg-%s.html" % page    # Name of the output file
        with open(file_name, 'wb') as file:
            file.write(response.body)  # Writing the file
        self.log("file saved %s" % file_name)

Save the file and run the program by entering the below command in the terminal.

(venv) PS C:\Users\Kresh\PycharmProjects\first_spider> scrapy crawl gfg

Note:-

  • Replace gfg with the name of your spider , i.e, the value assigned to ‘name’ inside the spider class.
  • In the source code, fill the empty ‘url_list’ with the target URL before running the spider.

Explanation of Code

  1. In context of python programming language, spider is just a class that has special methods associated with it to crawl and scrape webpages. So lets start with creating a class that inherits the base Spider class.
  2. ‘name’ is an attribute that defines the name of the spider. It must be unique.
  3. start_request() is a method that is called by scrapy when a spider has opened. It is called only once. It is used to initiate the process of scraping and can be used as a generator. 
  4. URLs are stored in a list and are scraped one by one using a ‘for’ loop.
  5. The ‘yield’ keyword is an inbuilt feature of Spider class that saves the data acquired after the completion of a request.
  6. parse() method is scrapy’s default callback method. Thus we don’t need to use a callback explicitly to call this method. It is used for processing the received response. The response received is given as a parameter to this method.  
  7. In the parse() method, the body of  response is written into the html file created, using file-handling methods. 

Output:

The output will get saved as a HTML file which can be seen in our scrapy project.

Example 2: Extraction of image files from webpages




# import section
import scrapy
  
# spider inheriting Spider base class
  
  
class GFGImageSpider (scrapy. Spider):
    name = "gfg_img"
    start_urls = ["https://practice.geeksforgeeks.org/"]
  
    def parse(self, response):
        # using xpath selector
        links = response.xpath("//img/@src")
        # to store html content in the form of string
        html = ""
  
        for link in links:
            # converting link to string
            url = link.get()
            # checking for images
            if any(extension in url for extension in [".jpg",
                                                      ".gif",
                                                      ".png"]):
                html += """<a href="{url}"
                target="_blank">
                <img src="{url}" height="33%"
                width="33%" />
                <a/>""". format(url=url)
                # creating a file to write html content
                with open("gfg_images.html", "a") as page:
                    page.write(html)
                    page.close()

Explanation of code

Output

Example 3:  Selective crawling

In the previous examples we have used inherited the ‘Spider’ class to create a spider. This class is also called BasicSpider or GenericSpider because it is simple and doesn’t have many functionalities. In this example, we are going to use the CrawlSpider class which allows us to define the behavior of  spider using rules.




# import section
import scrapy
from scrapy.spiders import CrawlSpider, Rule
from scrapy.linkextractors import LinkExtractor
  
  
class GFGSpidey(CrawlSpider):
    name = "gfg_spidey"
    # list of URLs to scrape
    allowed_domains = ["geeksforgeeks.org"]
    # creation of rules
    rules = (
        Rule(LinkExtractor(allow="c-arrays"), callback="parse_item"),
    )
    # method to parse
  
    def parse_item(self, response):
        # saving items via yield dictionary
        yield{
            "Title of article": response.css("div.head a::text").get(),
            "Tag present": response.css("div.item a::text").get()
        }

Explanation of code

Inspection of webpage

Note: Although web scraping is absolutely legal, most of the websites cannot be scraped since they prevent bot activities for security reasons. After all, web spider is indeed a bot!

Finding websites to scrape

Type ‘robots.txt’ at the end of the URL of the website that you need to scrape. The robots.txt is a file that gives you a list of bots that are not allowed in the website. If spiders are not present in the list of disallowed bots, you might scrape that website.

robots.txt

Applications of web spiders


Article Tags :