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 data from pages using JavaScript code. The Actor supports both recursive crawling and lists of URLs and automatically manages concurrency for maximum performance. This is Apify's basic tool for web crawling and scraping.

Do you want to learn more about this Actor?

Get a demo
RT

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

Closed

artbaggio opened this issue
6 days 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

  • 2.5k monthly users

  • 331 stars

  • >99% runs succeeded

  • 37 days response time

  • Created in Mar 2019

  • Modified 5 months ago