Search code examples
javascriptnode.jscheerio

How To Select one of the same multiple elements in cheerio nodejs?


I'm trying to scrape links from a page, but the problem I'm facing right now is that i want to scrape href from anchor tag, but it has multiple tags with no class inside them.

It looks something like this

<div class="class1">
<a href="sample.com">Some random text</a>
<a href="example.com">Some random text</a>
</div>

Now I want to get example.com but when i try find(".class1").find("a").attr("href"); it returns me sample.com.

I want to do something like this to get example.com instead of sample.com find(".class1").find("a")[1].attr("href"); returns example.com

please someone help me with this. I'm a newbie to cheerio and cheerio's documentation is so much confusing to me.


Solution

  • You can select the n-th <a> element using :

    find(".class1").find("a:nth-child(4)").attr("href");