How to get the innerText of an ID from an HTML String data that we got from axios?
I am new to web scraping in JavaScript. I used axios to make GET http request. I got the response.data will give the HTML content in String format. Now i want to get the innerText from an ID.
const axios = require('axios') ;
const url = "https://www.google.com" ;
axios.get(url).then(response=>{
const html = response.data ;
console.log(typeof html) ; // string
const name = document.getElementById('SIvCob').innerText ; // How can i write this line ?
console.log(name) ; // it will give error. I want it to give the innerText of ID 'SIvCov' from google's HTML Document.
}).catch(error=>{
console.log('Error');
})
You'll need to use a DOM parser. There are several available as npm
packages, such as cheerio
or dom-parser
(but again, those are only two of your options).
With your preferred DOM parser, you'd pass the string you receive into it to parse it, then use its features to retrieve the text content.
For instance, with cheerio
:
cheerio.load(html);
const name = $("#SIvCob").text();
Or with dom-parser
:
import DomParser from "dom-parser";
const parser = new DomParser();
const dom = parser.parseFromString(html);
const name = dom.getElementById('SIvCob').textContent;