The Wayback Machine - https://web.archive.org/web/20241128103739/https://www.geeksforgeeks.org/implementing-web-scraping-python-scrapy/
Open In App

Implementing Web Scraping in Python with Scrapy

Last Updated : 08 Nov, 2019
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Nowadays data is everything and if someone wants to get data from webpages then one way to use an API or implement Web Scraping techniques. In Python, Web scraping can be done easily by using scraping tools like BeautifulSoup. But what if the user is concerned about performance of scraper or need to scrape data efficiently.

To overcome this problem, one can make use of MultiThreading/Multiprocessing with BeautifulSoup module and he/she can create spider, which can help to crawl over a website and extract data. In order to save the time one use Scrapy.

With the help of Scrapy one can :

1. Fetch millions of data efficiently
2. Run it on server
3. Fetching data 
4. Run spider in multiple processes

Scrapy comes with whole new features of creating spider, running it and then saving data easily by scraping it. At first it looks quite confusing but it’s for the best.

Let’s talk about the installation, creating a spider and then testing it.

Step 1 : Creating virtual environment

It is good to create one virtual environment as it isolates the program and doesn’t affect any other programs present in the machine. To create virtual environment first install it by using :

sudo apt-get install python3-venv

Create one folder and then activate it :

mkdir scrapy-project && cd scrapy-project
python3 -m venv myvenv 

If above command gives Error then try this :

python3.5 -m venv myvenv

After creating virtual environment activate it by using :

source myvenv/bin/activate

 
Step 2 : Installing Scrapy module

Install Scrapy by using :

pip install scrapy

To install scrapy for any specific version of python :

python3.5 -m pip install scrapy

Replace 3.5 version with some other version like 3.6.
 
Step 3 : Creating Scrapy project

While working with Scrapy, one needs to create scrapy project.

scrapy startproject gfg

In Scrapy, always try to create one spider which helps to fetch data, so to create one, move to spider folder and create one python file over there. Create one spider with name gfgfetch.py python file.
 
Step 4 : Creating Spider

Move to the spider folder and create gfgfetch.py. While creating spider, always create one class with unique name and define requirements. First thing is to name the spider by assigning it with name variable and then provide the starting URL through which spider will start crawling. Define some methods which helps to crawl much deeper into that website. For now, let’s scrap all the URL present and store all those URL.




import scrapy
  
class ExtractUrls(scrapy.Spider):
      
    # This name must be unique always
    name = "extract"                 
  
    # Function which will be invoked
    def start_requests(self):
          
        # enter the URL here
        urls = ['https://www.geeksforgeeks.org/', ]
          
        for url in urls:
            yield scrapy.Request(url = url, callback = self.parse)


Main motive is to get each url and then request it. Fetch all the urls or anchor tags from it. To do this, we need to create one more method parse ,to fetch data from the given url.
 
Step 5 : Fetching data from given page
Before writing parse function, test few things like how to fetch any data from given page. To do this make use of scrapy shell. It is just like python interpreter but with the ability to scrape data from the given url. In short, its a python interpreter with Scrapy functionality.

scrapy shell URL

Note: Make sure to in the same directory where scrapy.cfg is present, else it will not work.

scrapy shell https://www.geeksforgeeks.org/

Now for fetching data from the given page, use selectors. These selectors can be either from CSS or from Xpath. For now, let’s try to fetch all url by using CSS Selector.

  • To get anchor tag :
    response.css('a')
  • To extract the data :
    links = response.css('a').extract()
  • For example, links[0] will show something like this :
    '<a href="https://www.geeksforgeeks.org/" title="GeeksforGeeks" rel="home">GeeksforGeeks</a>'
  • To get href attribute, use attributes tag.
    links = response.css('a::attr(href)').extract()

This will get all the href data which is very useful. Make use of this link and start requesting it.

Now, let’s create parse method and fetch all the urls and then yield it. Follow that particular URL and fetch more links from that page and this will keep on happening again and again. In short, we are fetching all url present on that page.

Scrapy, by default, filters those url which has already been visited. So it will not crawl the same url path again. But it’s possible that in two different pages there are two or more than two similar links. For example, in each page, the header link will be available which means that this header link will come in each page request. So try to exclude it by checking it.




# Parse function
def parse(self, response):
      
    # Extra feature to get title
    title = response.css('title::text').extract_first() 
      
    # Get anchor tags
    links = response.css('a::attr(href)').extract()     
      
    for link in links:
        yield 
        {
            'title': title,
            'links': link
        }
          
        if 'geeksforgeeks' in link:         
            yield scrapy.Request(url = link, callback = self.parse)


 
Below is the implementation of scraper :




# importing the scrapy module
import scrapy
  
class ExtractUrls(scrapy.Spider):
    name = "extract"
  
    # request function
    def start_requests(self):
        urls = [ 'https://www.geeksforgeeks.org', ]
          
        for url in urls:
            yield scrapy.Request(url = url, callback = self.parse)
  
    # Parse function
    def parse(self, response):
          
        # Extra feature to get title
        title = response.css('title::text').extract_first() 
          
        # Get anchor tags
        links = response.css('a::attr(href)').extract()     
          
        for link in links:
            yield 
            {
                'title': title,
                'links': link
            }
              
            if 'geeksforgeeks' in link:         
                yield scrapy.Request(url = link, callback = self.parse)


 
Step 6 : In last step, Run the spider and get output in simple json file

scrapy crawl NAME_OF_SPIDER -o links.json

Here, name of spider is “extract” for given example. It will fetch loads of data within few seconds.

Output :

Note : Scraping any web page is not a legal activity. Don’t perform any scraping operation without permission.



Reference : https://doc.scrapy.org/en/.



Similar Reads

Pagination using Scrapy - Web Scraping with Python
Pagination using Scrapy. Web scraping is a technique to fetch information from websites. Scrapy is used as a Python framework for web scraping. Getting data from a normal website is easier, and can be just achieved by just pulling the HTML of the website and fetching data by filtering tags. But what is the case when there is Pagination in Python an
3 min read
Scraping dynamic content using Python-Scrapy
Let's suppose we are reading some content from a source like websites, and we want to save that data on our device. We can copy the data in a notebook or notepad for reuse in future jobs. This way, we used scraping(if we didn't have a font or database, the form brute removes the data in documents, sites, and codes). But now there exist many tools f
4 min read
Automated Website Scraping using Scrapy
Scrapy is a Python framework for web scraping on a large scale. It provides with the tools we need to extract data from websites efficiently, processes it as we see fit, and store it in the structure and format we prefer. Zyte (formerly Scrapinghub), a web scraping development and services company, currently maintains it. What is a Web Crawler (Web
5 min read
Scraping a JSON response with Scrapy
Scrapy is a popular Python library for web scraping, which provides an easy and efficient way to extract data from websites for a variety of tasks including data mining and information processing. In addition to being a general-purpose web crawler, Scrapy may also be used to retrieve data via APIs. One of the most common data formats returned by AP
2 min read
Scraping Javascript Enabled Websites using Scrapy-Selenium
Scrapy-selenium is a middleware that is used in web scraping. scrapy do not support scraping modern sites that uses javascript frameworks and this is the reason that this middleware is used with scrapy to scrape those modern sites.Scrapy-selenium provide the functionalities of selenium that help in working with javascript websites. Other advantages
4 min read
Implementing web scraping using lxml in Python
Web scraping basically refers to fetching only some important piece of information from one or more websites. Every website has recognizable structure/pattern of HTML elements. Steps to perform web scraping :1. Send a link and get the response from the sent link 2. Then convert response object to a byte string. 3. Pass the byte string to 'fromstrin
3 min read
Implementing Web Scraping in Python with BeautifulSoup
There are mainly two ways to extract data from a website: Use the API of the website (if it exists). For example, Facebook has the Facebook Graph API which allows retrieval of data posted on Facebook.Access the HTML of the webpage and extract useful information/data from it. This technique is called web scraping or web harvesting or web data extrac
8 min read
Web Scraping CryptoCurrency price and storing it in MongoDB using Python
Let us see how to fetch history price in USD or BTC, traded volume and market cap for a given date range using Santiment API and storing the data into MongoDB collection. Python is a mature language and getting much used in the Cryptocurrency domain. MongoDB is a NoSQL database getting paired with Python in many projects which helps to hold details
4 min read
Web Scraping using lxml and XPath in Python
Prerequisites: Introduction to Web Scraping In this article, we will discuss the lxml python library to scrape data from a webpage, which is built on top of the libxml2 XML parsing library written in C. When compared to other python web scraping libraries like BeautifulSoup and Selenium, the lxml package gives an advantage in terms of performance.
3 min read
Web scraping from Wikipedia using Python - A Complete Guide
In this article, you will learn various concepts of web scraping and get comfortable with scraping various types of websites and their data. The goal is to scrape data from the Wikipedia Home page and parse it through various web scraping techniques. You will be getting familiar with various web scraping techniques, python modules for web scraping,
9 min read
Quote Guessing Game using Web Scraping in Python
Prerequisite: BeautifulSoup Installation In this article, we will scrape a quote and details of the author from this site http//quotes.toscrape.com using python framework called BeautifulSoup and develop a guessing game using different data structures and algorithm. The user will be given 4 chances to guess the author of a famous quote, In every ch
3 min read
How to Build Web scraping bot in Python
In this article, we are going to see how to build a web scraping bot in Python. Web Scraping is a process of extracting data from websites. A Bot is a piece of code that will automate our task. Therefore, A web scraping bot is a program that will automatically scrape a website for data, based on our requirements. Module neededbs4: Beautiful Soup(bs
8 min read
Clean Web Scraping Data Using clean-text in Python
If you like to play with API's or like to scrape data from various websites, you must've come around random annoying text, numbers, keywords that come around with data. Sometimes it can be really complicating and frustrating to clean scraped data to obtain the actual data that we want. In this article, we are going to explore a python library calle
2 min read
Web Scraping Financial News Using Python
In this article, we will cover how to extract financial news seamlessly using Python. This financial news helps many traders in placing the trade in cryptocurrency, bitcoins, the stock markets, and many other global stock markets setting up of trading bot will help us to analyze the data. Thus all this can be done with the help of web scraping usin
3 min read
Web Scraping Tables with Selenium and Python
Selenium is the automation software testing tool that obtains the website, performs various actions, or obtains the data from the website. It was chiefly developed for easing the testing work by automating web applications. Nowadays, apart from being used for testing, it can also be used for making tedious work interesting. Do you know that with th
4 min read
Reading selected webpage content using Python Web Scraping
Prerequisite: Downloading files in Python, Web Scraping with BeautifulSoup We all know that Python is a very easy programming language but what makes it cool are the great number of open source library written for it. Requests is one of the most widely used library. It allows us to open any HTTP/HTTPS website and let us do any kind of stuff we norm
3 min read
Spoofing IP address when web scraping using Python
In this article, we are going to scrap a website using Requests by rotating proxies in Python. Modules RequiredRequests module allows you to send HTTP requests and returns a response with all the data such as status, page content, etc. Syntax: requests.get(url, parameter) JSON JavaScript Object Notation is a format for structuring data. It is mainl
3 min read
Python | Tools in the world of Web Scraping
Web page scraping can be done using multiple tools or using different frameworks in Python. There are variety of options available for scraping data from a web page, each suiting different needs. First, let's understand the difference between web-scraping and web-crawling. Web crawling is used to index the information on the page using bots also kn
4 min read
Increase the speed of Web Scraping in Python using HTTPX module
In this article, we will talk about how to speed up web scraping using the requests module with the help of the HTTPX module and AsyncIO by fetching the requests concurrently. The user must be familiar with Python. Knowledge about the Requests module or web scraping would be a bonus. Required Module For this tutorial, we will use 4 modules - timere
4 min read
Web Scraping for Stock Prices in Python
Web scraping is a data extraction method that collects data only from websites. It is often used for data mining and gathering valuable insights from large websites. Web scraping is also useful for personal use. Python includes a nice library called BeautifulSoup that enables web scraping. In this article, we will extract current stock prices using
6 min read
Email Id Extractor Project from sites in Scrapy Python
Scrapy is open-source web-crawling framework written in Python used for web scraping, it can also be used to extract data for general-purpose. First all sub pages links are taken from the main page and then email id are scraped from these sub pages using regular expression. This article shows the email id extraction from geeksforgeeks site as a ref
8 min read
How To Follow Links With Python Scrapy ?
In this article, we will use Scrapy, for scraping data, presenting on linked webpages, and, collecting the same. We will scrape data from the website 'https://quotes.toscrape.com/'. Creating a Scrapy Project Scrapy comes with an efficient command-line tool, also called the 'Scrapy tool'. Commands are used for different purposes and, accept a differ
8 min read
Writing Scrapy Python Output to JSON file
In this article, we are going to see how to write scrapy output into a JSON file in Python. Using scrapy command-line shell This is the easiest way to save data to JSON is by using the following command: scrapy crawl <spiderName> -O <fileName>.json This will generate a file with a provided file name containing all scraped data. Note tha
2 min read
How to Install Python Scrapy on Windows?
Scrapy is a web scraping library that is used to scrape, parse and collect web data. Now once our spider has scrapped the data then it decides whether to: Keep the data.Drop the data or items.stop and store the processed data items. In this article, we will look into the process of installing the Scrapy module on Windows. Pre-requisites: The only t
2 min read
How to run Scrapy spiders in Python
In this article, we are going to discuss how to schedule Scrapy crawl execution programmatically using Python. Scrapy is a powerful web scraping framework, and it's often necessary to schedule the execution of a Scrapy crawl at specific intervals. Scheduling Scrapy crawl execution programmatically allows you to automate the process of scraping data
5 min read
Web Scraping - Legal or Illegal?
If you're connected with the term 'Web Scraping' anyhow, then you must come across a question - Is Web Scraping legal or illegal? Okay, so let's discuss it. If you look closely, you will find out that in today's era the biggest asset of any business is Data! Even the top giants like Facebook, Amazon, Uber are ruling because of the vast amount of da
5 min read
Web Scraping using Beautifulsoup and scrapingdog API
In this post we are going to scrape dynamic websites that use JavaScript libraries like React.js, Vue.js, Angular.js, etc you have to put extra efforts. It is an easy but lengthy process if you are going to install all the libraries like Selenium, Puppeteer, and headerless browsers like Phantom.js. But, we have a tool that can handle all this load
5 min read
Web Scraping Coronavirus Data into MS Excel
Prerequisites: Web Scraping using BeautifulSoup Coronavirus cases are increasing rapidly worldwide. This article will guide you on how to web scrape Coronavirus data and into Ms-excel. What is Web Scraping? If you’ve ever copy and pasted information from a website, you’ve performed the same function as any web scraper, only on a microscopic, manual
5 min read
Web Scraping - Amazon Customer Reviews
In this article, we are going to see how we can scrape the amazon customer review using Beautiful Soup in Python. Module neededbs4: Beautiful Soup(bs4) is a Python library for pulling data out of HTML and XML files. This module does not come built-in with Python. To install this type the below command in the terminal. pip install bs4 requests: Requ
5 min read
Web Scraping Without Getting Blocked
Web Scraping refers to the process of scraping/extracting data from a website using the HTTP protocol or web browser. The process can either be manual or it can be automated using a bot or a web crawler. Also, there is a misconception about web scraping being illegal, the truth is that it is perfectly legal unless you're trying to access non-public
7 min read
Practice Tags :
three90RightbarBannerImg