Scrapy Selectors as the name suggest are used to select some things. If we talk of CSS, then there are also selectors present that are used to select and apply CSS effects to HTML tags and text.
In Scrapy we are using selectors to mention the part of the website which is to be scraped by our spiders. Hence, to scrape the right data from the site, it is very important that we should select the tags which represent data correctly. There are many tools used for that.
Types of selectors:
In Scrapy, there are mainly two types of selectors, i.e. CSS selectors and XPath selectors. Both of them are performing the same function and selecting the same text or data but the format of passing the arguments is different in them.
- CSS selectors: Since CSS languages are defined in any HTML File, so we can use their selectors as a way to select parts of the HTML file in Scrapy.
- XPath selectors: It is a language used to select Nodes in XML documents and hence it can be used in HTML Files too since HTML Files can also be represented as XML documents.
Description:
Let's have an HTML File (index.html) as given below which we are to Scrap using our Spider and see how selectors are working. We will be working on Scrapy Shell to give commands to select data.
HTML
<html>
<head>
<title>Scrapy-Selectors</title>
</head>
<body>
<div id='Selectors'>
<h1> This is H1 Tag </h1>
<span class="SPAN1"> This is Class Selectors SPAN tag </span>
</div>
</body>
</html>
Below given is a view of our Scrapy Shell which we will be using:
Command to open shell:
Scrapy shell file:///C:/Users/Dipak/Desktop/index.html
Scrapy Shell activated to Crawl Spiders on Index.html File.Using Selectors:
Now we will discuss how to use selectors in Scrapy. Since there are mainly two types of it as given below:
CSS Selectors:
There are various formats for using CSS selectors under different cases. They are given below:
- Very Basic Start goes from selecting the basic tags in HTML file such as the <HTML> tag, <HEAD>, <BODY>, etc. So the below given is the basic format to select any tag in the HTML File using Scrapy.
Shell Command : response.css('html').get()
# Here response object calls CSS selector method to
# target HTML tag and get() method
# is used to select everything inside the HTML tag.
Output:The whole content of the HTML file is selected.- So, now it's time to modify our way of selecting, If we want to select only the inside text of the Tags or just want to select the attribute of any particular tag then we can follow the below-given syntax:
# To select the text inside the Tags
# excluding tags we have to use (::text)
# as our extension.
response.css('h1::text').get()
# To select the attributes details of
# any HTML tag we have to use below
# given syntax:
response.css('span').attrib['class']
Output of above commands.- If there are many same types of tags in the HTML File then we can use .getall() method instead of .get() to select all the tags. It returns a list of selected tags and their data.
- If the tag which we have to select is not mentioned in the file then CSS selectors return nothing. We can also provide default data to be returned if nothing is found.
Selects nothing.XPath Selectors:
The way these selectors work is similar to that how CSS selectors work instead the syntax differs only.
The below are the surtaxes which can be written in XPATH for selecting, what we have done earlier.
# This is to select the text part of
# title tag using XPATH
response.xpath('//title/text()')
response.xpath('//title/text()').get()
# This is how to select attributes
response.xpath('//span/@class').get()
XPATH selectors.
Properties:
1. We can nest selectors within one another. Since if our HTML file can contain elements inside the div tag, so we can nest the selectors to select a particular element in it. To achieve this we first have to select all the elements inside the div tag, and then we can select any particular element from it.
div_tag = response.xpath('//div')
div_tag.getall()
for tags in div_tag:
tag = tags.xpath('.//h1').get()
print({tag})
Use of Nesting in selectors
2. Next we can use our selectors with the regular expression also. If we don't know what is the name of the attributes or elements then we can use regular expressions too for selection. For this we have a method named ( .re()).
The .re() Method is used to select tags based on the content match. If the content inside the HTML tag matches with the regular expression inputted, then this method returns a list of that content. In the above HTML file, we are having two tags named h1 and span tag inside the DIV tag, and the text in these both tags has the same starting i.e. " This is ". So to select them based on regex we have to form their regular expression which is given below:
regexp = r'This\sis\s*(.*)' and we have to input this in our .re() method
So our code becomes
response.css('#Selectors *::text').re(r'This\sis\s*(.*)')
Using Regular expression for selecting the text
3. EXSLT Regular Expressions are also supported by scrapy spiders. We can use its method to select the items based on some new regular expressions. This extension provides two different namespaces to be used in XPath
- re: Used for making regular expressions.
- set: Used for set manipulation
We can use these namespaces to modify the select statement specified in our Xpath method.
Below is one of the given example:
Suppose we had added two h1 tag and name their class in our HTML file so now it looks like :
HTML
<html>
<head>
<title>Scrapy-Selectors</title>
</head>
<body>
<div id='Selectors'>
<h1 class='FirstH1'> This is H1 Tag </h1>
<h1 class='FirstH2'> This is Second H1 Tag </h1>
<h1 class='FirstH'> This is Third H1 Tag </h1>
<span class="SPAN1"> This is Class Selectors SPAN tag </span>
</div>
</body>
</html>
Now if we want to select both H1 tags using regexp then we can see that we have to select that tag that has a starting string first in the id part and the end integer doesn't matter.
So the code for this :
response.xpath('//h1[re:test(@class, "FirstH\d$")]').getall()
Here we are using re:test method to specify and test our regular expression on the class attribute of our h1 tag and regexp selects only those h1 tags whose class attribute values ends with an integer.
This was an example of using EXSLT in selectors in scrapy.
4. If want we can use both selectors merged together to enhance the way of selecting.
response.css('span').xpath('@class').get()
# CSS is used to select tag and XPATH is
# used to select attribute
Merging selectors.
Note:
- In XPath when we are using the nesting property of selectors then we should take care of a fact regarding Relative XPaths. Consider we selected a div tag as given below:
div_tag = response.xpath('//div')
This will select div tag and all the elements inside that tag. Now assume that the div tag contains some <a>tags within it. Now if we want to use nesting selectors and select the <a> tag then we would write
for a in div_tag.xpath('.//a'):
This is a relative path that tells the spider to select tag elements from only the path inside the div tag selected above. If we will write -
for a in div_tag('//a'):
It will select all the tag inside the HTML document. So we should take care of relative paths.
- We can use Google Chrome Extension named as SelectorGadget which is used to simplify the selecting task. Since all websites today if we inspect them, have very lengthy and hard to understand and search codes. So amidst them, we can use this extension which enables selecting the tags on Frontend only.
Similar Reads
Implementing Web Scraping in Python with Scrapy 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
5 min read
Getting Started With Scrapy
Scrapy Basics
Scrapy - Command Line ToolsPrerequisite: Implementing Web Scraping in Python with Scrapy Scrapy is a python library that is used for web scraping and searching the contents throughout the web. It uses Spiders which crawls throughout the page to find out the content specified in the selectors. Hence, it is a very handy tool to
5 min read
Scrapy - Item LoadersIn this article, we are going to discuss Item Loaders in Scrapy. Scrapy is used for extracting data, using spiders, that crawl through the website. The obtained data can also be processed, in the form, of Scrapy Items. The Item Loaders play a significant role, in parsing the data, before populating
15+ min read
Scrapy - Item PipelineScrapy is a web scraping library that is used to scrape, parse and collect web data. For all these functions we are having a pipelines.py file which is used to handle scraped data through various components (known as class) which are executed sequentially. In this article, we will be learning throug
10 min read
Scrapy - SelectorsScrapy Selectors as the name suggest are used to select some things. If we talk of CSS, then there are also selectors present that are used to select and apply CSS effects to HTML tags and text. In Scrapy we are using selectors to mention the part of the website which is to be scraped by our spiders
7 min read
Scrapy - ShellScrapy is a well-organized framework, used for large-scale web scraping. Using selectors, like XPath or CSS expressions, one can scrape data seamlessly. It allows systematic crawling, and scraping the data, and storing the content in different file formats. Scrapy comes equipped with a shell, that h
9 min read
Scrapy - SpidersScrapy 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
11 min read
Scrapy - Feed exportsScrapy is a fast high-level web crawling and scraping framework written in Python used to crawl websites and extract structured data from their pages. It can be used for many purposes, from data mining to monitoring and automated testing. This article is divided into 2 sections:Creating a Simple web
5 min read
Scrapy - Link ExtractorsIn this article, we are going to learn about Link Extractors in scrapy. "LinkExtractor" is a class provided by scrapy to extract links from the response we get while fetching a website. They are very easy to use which we'll see in the below post. Scrapy - Link Extractors Basically using the "LinkEx
5 min read
Scrapy - SettingsScrapy is an open-source tool built with Python Framework. It presents us with a strong and robust web crawling framework that can easily extract the info from the online page with the assistance of selectors supported by XPath. We can define the behavior of Scrapy components with the help of Scrapy
7 min read
Scrapy - Sending an E-mailPrerequisites: Scrapy Scrapy provides its own facility for sending e-mails which is extremely easy to use, and itâs implemented using Twisted non-blocking IO, to avoid interfering with the non-blocking IO of the crawler. This article discusses how mail can be sent using scrapy. For this MailSender
2 min read
Scrapy - ExceptionsPython-based Scrapy is a robust and adaptable web scraping platform. It provides a variety of tools for systematic, effective data extraction from websites. It helps us to automate data extraction from numerous websites. Scrapy Python Scrapy describes the spider that browses websites and gathers dat
7 min read
Data Collection and Management
Data Extraction and Export
How to Convert Scrapy item to JSON?Prerequisite:Â scrapyJSON Scrapy is a web scraping tool used to collect web data and can also be used to modify and store data in whatever form we want. Whenever data is being scraped by the spider of scrapy, we are converting that raw data to items of scrapy, and then we will pass that item for fur
8 min read
Saving scraped items to JSON and CSV file using ScrapyIn this article, we will see how to use crawling with Scrapy, and, Exporting data to JSON and CSV format. We will scrape data from a webpage, using a Scrapy spider, and export the same to two different file formats. Here we will extract from the link  http://quotes.toscrape.com/tag/friendship/. This
6 min read
How to get Scrapy Output File in XML File?Prerequisite: Implementing Web Scraping in Python with Scrapy Scrapy provides a fast and efficient method to scrape a website. Web Scraping is used to extract the data from websites. In Scrapy we create a spider and then use it to crawl a website. In this article, we are going to extract population
2 min read
Scraping a JSON response with ScrapyScrapy 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.
2 min read
Logging in ScrapyScrapy is a fast high-level web crawling and scraping framework written in Python used to crawl websites and extract structured data from their pages. It can be used for many purposes, from data mining to monitoring and automated testing. As developers, we spend most of our time debugging than writi
3 min read
Appliaction And Projects
How to use Scrapy to parse PDF pages online?Prerequisite: Scrapy, PyPDF2, URLLIB In this article, we will be using Scrapy to parse any online PDF without downloading it onto the system. To do that we have to use the PDF parser or editor library of Python know as PyPDF2. PyPDF2 is a pdf parsing library of python, which provides various method
3 min read
How to download Files with Scrapy ?Scrapy is a fast high-level web crawling and web scraping framework used to crawl websites and extract structured data from their pages. It can be used for a wide range of purposes, from data mining to monitoring and automated testing. In this tutorial, we will be exploring how to download files usi
8 min read
Automated Website Scraping using ScrapyScrapy 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,
5 min read
Writing Scrapy Python Output to JSON fileIn 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 provi
2 min read
Pagination using Scrapy - Web Scraping with PythonPagination 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
3 min read
Email Id Extractor Project from sites in Scrapy PythonScrapy 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 e
8 min read
Scraping Javascript Enabled Websites using Scrapy-SeleniumScrapy-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
4 min read
How to use Scrapy Items?In this article, we will scrape Quotes data using scrapy items, from the webpage https://quotes.toscrape.com/tag/reading/. The main objective of scraping, is to prepare structured data, from unstructured resources. Scrapy Items are wrappers around, the dictionary data structures. Code can be written
9 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 ar
9 min read
Difference between BeautifulSoup and Scrapy crawlerWeb scraping is a technique to fetch data from websites. While surfing on the web, many websites donât allow the user to save data for personal use. One way is to manually copy-paste the data, which both tedious and time-consuming. Web Scraping is the automation of the data extraction process from w
3 min read
Python - How to create an ARP Spoofer using Scapy?ARP spoofing is a malicious attack in which the hacker sends falsified ARP in a network. Every node in a connected network has an ARP table through which we identify the IP address and the MAC address of the connected devices. What aim to send an ARP broadcast to find our desired IP which needs to b
6 min read