Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to get a certain element from a body?

I use node-fetch , and I get the body of the site this way:

import fetch from 'node-fetch';

(async () => {
    const response = await fetch('link');
    const body = await response.text().

    console.log(body);
})()

The console displays the full body of the entire page. But I want to get a specific element with a certain class. How do I change the code to do this?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Well, you’ve already achieved obtaining a string that contains the entire html of the page.

Now you can write code that extracts the part you want from that string. You said you’re wanting to extract an element that has a particular class.

As moonwave99 commented, you could use cheerio, or some other html parser to extract the element with the class name you’re targeting.

Or, if you want to avoid using an outside package, you could just write a regular expression to match the HTML element you want from that html string:

let wholeHTML =
`<html>
<p>Paragraph 1</p>
<p class="classIwant">Paragraph 2</p>
<p>Paragraph 3</p>
</html>`;

let rx = /<p class="classIwant".*\/p>/gm;
let matches = wholeHTML.match(rx);
console.log(matches[0]);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading