Web Scraper avatar

Web Scraper

Try for free

No credit card required

Go to Store
Web Scraper

Web Scraper

apify/web-scraper
Try for free

No credit card required

Crawls arbitrary websites using the Chrome browser and extracts structured data from web pages using a provided JavaScript function. The Actor supports both recursive crawling and lists of URLs, and automatically manages concurrency for maximum performance.

RT

Is it Possible to extract the href attribute inside a link HTML tag <a href="...">?

Closed
artbaggio opened this issue
a month ago

My goal is to grab the href attribute inside every link on the HTML code of the page.

I am using $("a:any-link") to select all the links, but it returns only the first link. How can I return all links.

And when I do return all links, how can I retrieve the link inside the href attribute of the tag?

jindrich.bar avatar

Hello and thank you for your interest in this Actor!

The JQuery's attr method returns the attribute value for the first element in the selection (see docs here). To collect the attribute values for all the elements in the collection, you have to use something like map() with get() - see my example snippet below:

1const linksJQuery = $('a[href]').map(function() {
2    return $(this).attr('href')
3}).get()

Note that the page function is run inside of the browser environment though - if you have more experience with regular "vanilla" Javascript DOM API, you can definitely use just that:

const linksDOMApi = [...document.querySelectorAll('a[href]')].map(x => x.getAttribute('href'));

Both those examples should yield the same results.

I'll close this issue now, but feel free to ask additional questions if you have any. Cheers!

Developer
Maintained by Apify

Actor Metrics

  • 3.3k monthly users

  • 456 bookmarks

  • >99% runs succeeded

  • 4.8 days response time

  • Created in Mar 2019

  • Modified a month ago