How Xpath Plays Vital Role In Web Scraping

Posted on Oct 18, 2019
The skills I demoed here can be learned through taking Data Science with Machine Learning bootcamp with NYC Data Science Academy.

 

XPath is a language for finding information in structured documents like XML or HTML. You can say that XPath is (sort of) SQL for XML or HTML files. XPath is used to navigate through elements and attributes in an XML or HTML document.

To understandΒ XPathΒ we must be clear about elements and nodes which are the building blocks of XML and HTML. Let’s talk about them. Here is an example element in an HTML document:

Β Β Β <a class=”hyperlink” href=http://www.google.com>google</a>

Copy the above text to a file, name it asΒ sample.htmlΒ and open it in a browser. This will end up as a text link displaying the words β€œgoogle” and it will take you to www.google.com. For each element there are three main parts:Β The type,Β the attributes, andthe text. They are listed below:

Β a Β  Β  Β  Β  Β  Β  Β  Β  Β  Β  Β  Β  Β  Β  Β  Β  Type
class, Β href Β  Β  Β  Β  Β  Β  Β  Β Attributes
google Β  Β  Β  Β  Β  Β  Β  Β  Β  Β  Β  TextΒ 


Let’s grab some XPath developer tools. I am onΒ Firebug for FirefoxΒ or you can useΒ Chrome’s developer tools. We will now form some XPath expressions to extract data from the above element. We will also verify the XPath by using Firebug Console.


For extracting the text β€œgoogle”:

Β Β Β //a[@href]/text() Β Β Β 

Β Β Β //a[@class=”hyperlink”]/text()
Β Β 

For extracting the hyperlink i.e. ”www.google.com” :

Β  Β //a/@href
//a[@class=”hyperlink”]/@href

That’s all with a single element but in reality, you need to deal with more complex forms.

Let’s proceed to the idea of nodes, and its familial relationship of HTML elements. Look at this example code:

 

 

<div title=”Section1β€³>

Β Β Β <table id=”Search”>

Β Β Β Β Β Β Β <tr class=”Yahoo”>Yahoo Search</tr>

Β Β Β Β Β Β Β <tr class=”Google”>Google Search</tr>

Β Β Β </table>

</div>

 

Notice theΒ </div>Β at the bottom? That means theΒ tableΒ andΒ trΒ elements are contained within theΒ div. These other elements are considered descendants of theΒ div. TheΒ tableΒ is a child, and theΒ trΒ is a grandchild (and so on and so forth). The twoΒ trΒ elements are considered siblings each other. This is vital, as XPath uses these relationships to find your element.


So suppose you want to find the Google item. Any of the following expressions will work:

Β Β Β //tr[@class=’Google’]
Β Β Β //div/table/tr[2]
Β  //div[@title=”Section1β€³]//tr[text()=”Google Search”]

So let’s analyze the expressions. We start at the top element (also known as a node). TheΒ //Β means to search all descendants,Β /Β means to just look at the current element’s children. SoΒ //divΒ means look through all descendants for aΒ divΒ element. The bracketsΒ []Β specify something about that element. So we can look for an attribute with theΒ @Β symbol, or look for text with theΒ text()Β function. We can chain as many of these together as we can.

Here is a quick reference:

Β Β Β //Β Β Β Β  Β  Β  Β  Β  Search all descendant elements
Β Β Β /Β Β Β Β  Β  Β  Β  Β  Β Search all child elements
Β Β Β []Β Β  Β  Β  Β  Β  Β  The predicate (specifies something about the element you are looking for)
Β  Β @Β Β  Β  Β  Β  Β  Specifies an element attribute. (For example, @title)
Β  Β Β 
Β Β Β . Β Β Β Β Β  Β  Β  Β  Β  Specifies the current node (useful when you want to look for an element’s children in the predicate)
Β Β Β .. Β Β Β  Β  Β  Β  Β  Β Specifies the parent node
Β  text()Β Β  Β  Β  Gets the text of the element.
Β Β Β Β 
In the context of web scraping,Β XPath is a nice tool to have in your belt, as it allows you to write specifications of document locations more flexibly than CSS selectors.

 

Read the original article here:

How Xpath Plays Vital Role In Web Scraping

The next session of this article wil be published soon.

About Author

Related Articles

Leave a Comment

No comments found.

View Posts by Categories


Our Recent Popular Posts


View Posts by Tags

#python #trainwithnycdsa 2019 2020 Revenue 3-points agriculture air quality airbnb airline alcohol Alex Baransky algorithm alumni Alumni Interview Alumni Reviews Alumni Spotlight alumni story Alumnus ames dataset ames housing dataset apartment rent API Application artist aws bank loans beautiful soup Best Bootcamp Best Data Science 2019 Best Data Science Bootcamp Best Data Science Bootcamp 2020 Best Ranked Big Data Book Launch Book-Signing bootcamp Bootcamp Alumni Bootcamp Prep boston safety Bundles cake recipe California Cancer Research capstone car price Career Career Day citibike classic cars classpass clustering Coding Course Demo Course Report covid 19 credit credit card crime frequency crops D3.js data data analysis Data Analyst data analytics data for tripadvisor reviews data science Data Science Academy Data Science Bootcamp Data science jobs Data Science Reviews Data Scientist Data Scientist Jobs data visualization database Deep Learning Demo Day Discount disney dplyr drug data e-commerce economy employee employee burnout employer networking environment feature engineering Finance Financial Data Science fitness studio Flask flight delay gbm Get Hired ggplot2 googleVis H20 Hadoop hallmark holiday movie happiness healthcare frauds higgs boson Hiring hiring partner events Hiring Partners hotels housing housing data housing predictions housing price hy-vee Income Industry Experts Injuries Instructor Blog Instructor Interview insurance italki Job Job Placement Jobs Jon Krohn JP Morgan Chase Kaggle Kickstarter las vegas airport lasso regression Lead Data Scienctist Lead Data Scientist leaflet league linear regression Logistic Regression machine learning Maps market matplotlib Medical Research Meet the team meetup methal health miami beach movie music Napoli NBA netflix Networking neural network Neural networks New Courses NHL nlp NYC NYC Data Science nyc data science academy NYC Open Data nyc property NYCDSA NYCDSA Alumni Online Online Bootcamp Online Training Open Data painter pandas Part-time performance phoenix pollutants Portfolio Development precision measurement prediction Prework Programming public safety PwC python Python Data Analysis python machine learning python scrapy python web scraping python webscraping Python Workshop R R Data Analysis R language R Programming R Shiny r studio R Visualization R Workshop R-bloggers random forest Ranking recommendation recommendation system regression Remote remote data science bootcamp Scrapy scrapy visualization seaborn seafood type Selenium sentiment analysis sentiment classification Shiny Shiny Dashboard Spark Special Special Summer Sports statistics streaming Student Interview Student Showcase SVM Switchup Tableau teachers team team performance TensorFlow Testimonial tf-idf Top Data Science Bootcamp Top manufacturing companies Transfers tweets twitter videos visualization wallstreet wallstreetbets web scraping Weekend Course What to expect whiskey whiskeyadvocate wildfire word cloud word2vec XGBoost yelp youtube trending ZORI