Saeed Heidarizarei
Saeed Heidarizarei

Reputation: 8946

Fetching html with cheerio

I'm using cheerio, How Can I Get content?

My Code is okey with This:

request('https://example.com', function (error, response, html) {
  if (!error && response.statusCode == 200) {
    const $ = cheerio.load(html);
      console.log(html);
  }
});

I need to get ģ‚¬ģ“ė“œ from content:

<meta property="og:description" content="šŸ‘¤ I'm Jack">
<meta property="og:title" content="ģ‚¬ģ“ė“œ">  // How to Get `ģ‚¬ģ“ė“œ` and print in console.log?

Upvotes: 0

Views: 1048

Answers (2)

Saeed Heidarizarei
Saeed Heidarizarei

Reputation: 8946

First way: console.log($("meta[property='og:title']").attr("content")); Solved By @adz5A

Secend way: console.log($("meta").eq(1).attr("content"));

.get() returns a DOM object.
Cheerio is not a browser, so the DOM api is not available.

Upvotes: 0

adz5A
adz5A

Reputation: 2032

request('https://example.com', function (error, response, html) {
  if (!error && response.statusCode == 200) {
      const $ = cheerio.load(html);
      console.log($("meta[property='og:title']").attr("content"));    
  }
});

Side node ( related to a previous error in the answer ) :

You should be aware when using cheerio that it only emulates some aspect of the jQuery api and does not recreate a whole DOM. Which means that contrary to a previous version of this answer you cannot do :

$("meta").get(1).getAttribute("origin"); which will result in a TypeError for trying to call on undefined. Cheerio builds a representation of the DOM upon which a subset of the jQuery api is implemented. The get api exists but will return this representation and not the standard DOM one, and there are no getAttributemethod attached to the cheerio representation. If you want a complete DOM representation and jQuery you need to use something like jsdom.

Upvotes: 1

Related Questions