How to scrape HTML from a website Using Javascript?
Tags: scrape, javascript, axios, cheerio
Published: 2021-04-13 08:22:10

<blockquote>Do you plan to scrape websites using JavaScript? With the help of the Node.js platform and its associated libraries, you can use JavaScript to develop web scrapers that can scrape data from any website you like.</blockquote>
<p><img class="aligncenter size-full wp-image-6073" src="https://www.bestproxyreviews.com/wp-content/uploads/2020/09/web-scraping-with-javascript.jpg" alt="web scraping with javascript" width="1000" height="555" /> We are in an era where businesses depend largely on data, and the Internet is a huge source of data with textual data being the most important. Social and business researchers are interested in collecting data from websites that have data of interest to them. Unfortunately, most websites do not make it easy for data scientists to collect the required data. For this reason, researchers have to use automated means to collect these data on their own. This automated means of collecting publicly accessible data on web pages using <a href="https://dev.to/younglbrownh/best-web-scraping-tools-ultimate-web-scraper-list-amb">web scrapers</a> is known as web scraping.</p>
<p>Web scrapers can be developed using any programming language that is Turing complete. Java, PHP, Python, JavaScript, C/C++, and C#, among others, have been used for writing web scrapers. Being that as it may, some languages are much more popular than others as far as developing web scrapers are concerned. JavaScript is not a popular choice. In recent times, its popularity as a language for developing web scrapers is on the rise &ndash; thanks to the availability of web scraping libraries. In this article, I will be showing you how to develop web scrapers using JavaScript.</p>
<hr />
<h2 style="text-align: center;"><strong>Node.js &ndash; The Game Changer</strong></h2>
<p>JavaScript was originally developed for frontend web development to add interactivity and responsiveness to web pages. Outside of a browser, JavaScript cannot run. For this reason, you cannot use it for backend development as you can use the likes of <a href="https://medium.com/@barbaraulowee/python-web-scraping-libraries-and-framework-77b36b7cb435">Python</a>, Java, and C++.&nbsp; This then means that you will need to be proficient in two languages to be able to do both frontend and backend development. However, Developers thought that JavaScript is a complete programming language and, as such, shouldn&rsquo;t be confined to only the browser environment. <img class="aligncenter size-full wp-image-6071" src="https://www.bestproxyreviews.com/wp-content/uploads/2020/09/Nodejs.jpg" alt="Nodejs" width="1000" height="525" /> This led Ryan Dahl to develop Node.js. Node.js is a JavaScript runtime environment built on Chrome&rsquo;s V8 JavaScript Engine. With Node.js, you can write codes and get them to run on PCs and servers, just like PHP, Java, and Python. This now made many developers take JavaScript as a complete language to be taken seriously &ndash; and many libraries and frameworks were developed for it to make programming backend using JavaScript easily. With Node.js, you can now use one language to write codes for both frontend and backend.</p>
<p>As a JavaScript developer, you can develop a complete web scraper using JavaScript, and you will use Node.js to run it. I will show you how to code a web scraper using JavaScript and some Node.js libraries.</p>
<hr />
<h2 style="text-align: center;"><strong>Installations and Setup</strong></h2>
<p><img class="aligncenter size-full wp-image-6068" src="https://www.bestproxyreviews.com/wp-content/uploads/2020/09/Node.js-libraries.jpg" alt="Node.js libraries" width="1000" height="508" /> Unlike the JavaScript runtime that comes installed in every modern browser, you will need to install Node.js for you to use it for your development. You can install Node.js from <a href="https://nodejs.org/en/" target="_blank" rel="noopener noreferrer">the Node.js official website</a> &ndash; file size is less than 20MB for Windows users. After installing Node.js, you can enter the below code in your command line to see if it has been installed successfully.</p>
<pre><strong>Node</strong></pre>
<p>if no error message is returned, then Node has been installed successfully. You can also confirm by looking out for the Node.js application in your list of installed programs. After installation, the next step is to install the necessary libraries/modules for web scraping. For this tutorial, I will advise you to create a new folder in your desktop and name it web scraping. Then launch Command Prompt (MS-DOS/ command line) and navigate to the folder using the command below.</p>
<pre><strong>cd desktop/web scraper</strong></pre>
<p>Now, let start installing the Node.js packages for web scraper &ndash; don&rsquo;t close Command Prompt yet.</p>
<ul>
<li>
<h3><strong>Axios</strong></h3>
</li>
</ul>
<p>The Axios module is one of the most important web scraping libraries. It is an HTTP Client, just like a browser that sends web requests and gets back a response for you. You will be using it to download pages you want to scrape data from. To installAxios, use the code below.</p>
<pre><strong>npm install axios</strong></pre>
<ul>
<li>
<h3><strong>Cheerio</strong></h3>
</li>
</ul>
<p>Cheerio is a lightweight library you can use to transverse the DOM of the HTML page downloaded using Axios for the purpose of collecting the required data. Its syntax is like that of jQuery, and as such, you will have no problem using it if you already know how to make use of jQuery. Use the below command to install it.</p>
<pre><strong>npm install request</strong></pre>
<ul>
<li>
<h3><strong>Puppeteer</strong></h3>
</li>
</ul>
<p>If you are scraping from static pages, the libraries above will do the work. However, when you intend to scrape from pages that its contents are dynamically generated and depend on JavaScript evens to load, then Axios isn&rsquo;t useful as it only downloads what the server sends to it when it initials a request.&nbsp; For dynamic websites that depend on JavaScript events to load content, you will need a browser automation tool to help you control a browser so that all contents will load,and then you can scrape them.</p>
<pre><strong>npm install puppeteer</strong></pre>
<hr />
<h2 style="text-align: center;"><strong>Scraping from Static Websites</strong></h2>
<p>Scraping from static web pages is the easiest &ndash; when we are not putting anti-scraping systems into consideration. This is because, for static web pages, all that is required is for you to use an HTTP Client (Axios) to request for the content of a page, the website&rsquo;s server will send back a response as HTML. You can then make use of Cheerio to transverse the DOM and scrape the required data. In the example below, I use JavaScript to scrape the text within the h1 tag from <a href="https://example.com/" target="_blank" rel="noopener noreferrer">https://example.com/</a>. In the code below, I use Axiosto download the whole page and then Cheerio for collecting traversing the DOM and scraping the text within the h1 tag.</p>
<pre>constaxios = require("axios")

const cheerio = require("cheerio")

async function fetchHTML(url) {

const{ data } = await axios.get(url)

&nbsp; return cheerio.load(data)

}

const $ = await fetchHTML("https://example.com")

// Print the full HTML

console.log(`Site HTML: ${$.html()}\n\n`)

// Print some specific page content

console.log(`First h1 tag: ${$('h1').text()}`)</pre>
<hr />
<h2 style="text-align: center;"><strong>Scraping Dynamic Websites</strong></h2>
<p>Dynamic websites pose a serious challenge to web scraper. Websites on the Internet were initially developed as static websites with little to no form of interactivity. For these websites, when you send a request for a page, all the content for that page is loaded at ones &ndash; this is the model that is easiest for web scrapers to scrape. However, with the advent of dynamic websites, many pages on the Internet do not get their content loaded at ones. Some of the content depends on JavaScript events. If you are posed with scraping a website like this, you will need to use Puppeteer.</p>
<p>What Puppeteer does is that it controls Chrome to visit the website, trigger the JavaScript events that will load content, and then when content is loaded, you can then scrape the required data out. There is a lot you can do with Puppeteer. In the below example, the code scrapes the title and summary of <a href="https://www.imdb.com/title/tt1596343/" target="_blank" rel="noopener noreferrer">the Fast Five movies from IMDb</a>. There is more you can do with Puppeteer; <a href="https://devdocs.io/puppeteer/" target="_blank" rel="noopener noreferrer">read the Puppeteer documentation here</a> to learn more about its APIs and usage.</p>
<pre>const puppeteer = require("puppeteer");

async function collectData() {

const browser = await puppeteer.launch();

const page = await browser.newPage();

&nbsp; await page.goto

("https://www.imdb.com/title/tt1013752/");

const data = await page.evaluate(() =&gt; {

const title = document.querySelector(

&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; "#title-overview-widget &gt;div.vital&gt;

div.title_block&gt; div &gt;div.titleBar&gt;

div.title_wrapper&gt; h1"

).innerText;

const summary = document.querySelector(

&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; "#title-overview-widget &gt;

div.plot_summary_wrapper&gt;div.plot_summary&gt;

div.summary_text"

).innerText;

&nbsp;&nbsp;&nbsp; // This object will be stored in the data variable

&nbsp;&nbsp;&nbsp; return {

&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; title,

&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; summary,

&nbsp;&nbsp;&nbsp; };

&nbsp; });

&nbsp; await browser.close();

}

collectData();</pre>
<hr />
<h2 style="text-align: center;"><strong>A Note About Anti-Scraping Techniques</strong></h2>
<p>Looking at the codes above, I didn&rsquo;t incorporate techniques to bypass anti-bot systems. This is because the tutorial is minimalistic and a proof of concept. In reality, if you develop your own web scrapers and do not put into consideration anti-scraper systems, your bot will be blocked after a few hundred requests. This is because websites do not want to be scrapped as it adds no value to them &ndash; instead, it adds to their running cost. For this reason, they put in place anti-scraping systems to discourage web scraping and other forms of automated access.</p>
<p>The most popular anti-scraping techniques used by websites include IP tracking and block, and Captcha systems. Some websites use cookies, local storage, and browser fingerprinting to prevent bot traffic too. So, I will advise you to <a href="https://www.npmjs.com/package/axios" target="_blank" rel="noopener noreferrer">read the Axion documentation</a> in order to learn how to use proxies, change user-agent string, and other headers, as well as rotate them.For a more comprehensive article on how to evade blocks, read this article &ndash; <a href="https://www.bestproxyreviews.com/scrape-a-website-never-get-blacklisted/" target="_blank" rel="noopener noreferrer">How to Scrape Websites and Never Get Blocked</a>.</p>
<pre style="text-align: center;"><strong>Conclusion</strong></pre>
<p>With the development of Node.js, it is time for everyone that has looked down on JavaScript to know that JavaScript is like every other programming language. Unlike in the past, you can now develop web scraper in JavaScript that requires no browser to run &ndash; it will run on a server or your local PC with the help of Node. Node goes crape any website you like with the help of&nbsp; JavaScript, Node.js, <a href="https://www.bestproxyreviews.com/different-types-of-proxies/">proxies</a>, and anti-Captcha systems.</p>