Getting a list of all URLs on a website (meaning crawling multiple pages) is significantly more complex than getting them from a single page due to security restrictions (Same-Origin Policy) in browsers.
Therefore, I'll provide two solutions:
- Browser-based JavaScript: For getting URLs from the currently loaded page.
- Node.js (Server-side) JavaScript: For truly crawling an entire website. This is the appropriate tool for "all URLs on a website."
1. Browser-based JavaScript (For the current page only)
This code will run in your browser's console or as part of a script on an HTML page. It will only find links present in the DOM of the page it's currently running on.
function getPageUrlsWithAttributes() {
const urlsData = [];
const allLinks = document.querySelectorAll('a');
allLinks.forEach(link => {
const url = link.href; // .href property always returns an absolute URL
const textInsideATag = link.textContent.trim();
// Find the nearest h1 or h2 tag ancestor
let nearestHeadingText = null;
let currentElement = link;
// Traverse up the DOM tree until a h1/h2 or the body is found
while (currentElement && currentElement !== document.body) {
if (currentElement.nodeType === Node.ELEMENT_NODE) { // Ensure it's an element
if (currentElement.tagName === 'H1' || currentElement.tagName === 'H2') {
nearestHeadingText = currentElement.textContent.trim();
break;
}
}
currentElement = currentElement.parentElement;
}
// Alternative for finding nearest ancestor (more concise, but might need polyfill for older browsers)
// const nearestHeading = link.closest('h1, h2');
// const nearestHeadingText = nearestHeading ? nearestHeading.textContent.trim() : null;
urlsData.push({
url: url,
textInsideATag: textInsideATag,
nearestH1OrH2Text: nearestHeadingText
});
});
return urlsData;
}
// --- How to use in your browser's console ---
// 1. Navigate to any website.
// 2. Open the developer console (F12 or Ctrl+Shift+I).
// 3. Paste the `getPageUrlsWithAttributes` function definition.
// 4. Run:
// const websiteUrls = getPageUrlsWithAttributes();
// console.log(websiteUrls);
// console.log(`Found ${websiteUrls.length} URLs on this page.`);
Explanation:
document.querySelectorAll('a'): Selects all <a> (anchor) elements on the page.
link.href: This property always returns the absolute URL, even if the href attribute in the HTML is relative (e.g., /about).
link.textContent.trim(): Gets the visible text content of the link and removes leading/trailing whitespace.
- Finding
h1 or h2:
- The
closest('h1, h2') method is ideal for this, as it efficiently searches up the DOM tree for the nearest ancestor element matching the selector. I've also provided a manual while loop for broader browser compatibility or if you want to understand the traversal.
- If no
h1 or h2 ancestor is found, closest() returns null, and nearestHeadingText will remain null.
Limitations:
- Same-Origin Policy: This script can only access elements on the current page. It cannot navigate to other pages or load their content from a different origin (domain, protocol, port) due to browser security restrictions.
- Dynamic Content: If links are loaded dynamically after the initial page load via JavaScript (e.g., infinite scroll), you might need to run this function after that content has appeared or use a
MutationObserver.
2. Node.js (Server-side) JavaScript (For crawling an entire website)
This solution will run on your local machine using Node.js. It will make HTTP requests to fetch pages, parse their HTML, extract links, and then recursively visit those links within the same domain.
Prerequisites:
-
Node.js installed: Download from nodejs.org.
-
Required packages: You'll need axios for making HTTP requests and cheerio for parsing HTML (it provides a jQuery-like syntax for server-side DOM manipulation).
Install them in your project directory:
npm init -y
npm install axios cheerio
crawler.js
const axios = require('axios');
const cheerio = require('cheerio');
const { URL } = require('url'); // Node.js built-in URL parser
async function crawlWebsite(startUrl, maxDepth = 2) {
const visitedUrls = new Set(); // To avoid infinite loops and reprocessing
const urlsToVisit = [{ url: startUrl, depth: 0 }]; // Queue of URLs to visit
const websiteData = []; // To store the results
while (urlsToVisit.length > 0) {
const { url: currentUrl, depth } = urlsToVisit.shift();
// Normalize URL and check if already visited
let parsedUrl;
try {
parsedUrl = new URL(currentUrl);
// Ensure we only crawl within the initial domain
if (parsedUrl.hostname !== new URL(startUrl).hostname) {
continue;
}
} catch (error) {
console.warn(`Invalid URL encountered: ${currentUrl} - Skipping.`);
continue;
}
const normalizedUrl = parsedUrl.href;
if (visitedUrls.has(normalizedUrl)) {
continue;
}
if (depth > maxDepth) {
console.log(`Max depth reached for: ${normalizedUrl}`);
continue;
}
visitedUrls.add(normalizedUrl);
console.log(`Crawling (${depth}): ${normalizedUrl}`);
try {
const response = await axios.get(normalizedUrl, {
// Optional: set a user-agent to avoid being blocked by some sites
headers: {
'User-Agent': 'Mozilla/5.0 (compatible; MyWebsiteCrawler/1.0)'
}
});
const $ = cheerio.load(response.data);
// Extract data from current page's links
$('a').each((i, element) => {
const linkElement = $(element);
const href = linkElement.attr('href');
let absoluteLink;
if (href) {
try {
// Resolve relative URLs to absolute
absoluteLink = new URL(href, normalizedUrl).href;
} catch (e) {
console.warn(`Could not resolve link: ${href} on ${normalizedUrl}`);
return; // Skip this link
}
// Ensure it's still within the same domain
if (new URL(absoluteLink).hostname === parsedUrl.hostname) {
const textInsideATag = linkElement.text().trim();
// Find the nearest h1 or h2 tag ancestor using Cheerio's .closest()
const nearestHeading = linkElement.closest('h1, h2');
const nearestH1OrH2Text = nearestHeading.length ? nearestHeading.text().trim() : null;
websiteData.push({
url: absoluteLink,
textInsideATag: textInsideATag,
nearestH1OrH2Text: nearestH1OrH2Text
});
// Add new internal links to the queue for further crawling
if (!visitedUrls.has(absoluteLink)) {
urlsToVisit.push({ url: absoluteLink, depth: depth + 1 });
}
}
}
});
} catch (error) {
console.error(`Error crawling ${normalizedUrl}: ${error.message}`);
}
}
return websiteData;
}
// --- How to use ---
// Replace with the actual URL you want to crawl
const targetWebsite = 'http://quotes.toscrape.com/'; // Example: A simple site to scrape
const crawlDepth = 1; // 0 for only the starting page, 1 for links on start page, etc.
crawlWebsite(targetWebsite, crawlDepth)
.then(data => {
console.log('\n--- Crawl Results ---');
// Filter out duplicate URLs in the final results if needed
const uniqueUrls = Array.from(new Set(data.map(item => item.url)))
.map(url => data.find(item => item.url === url));
console.log(JSON.stringify(uniqueUrls, null, 2));
console.log(`\nTotal unique URLs found: ${uniqueUrls.length}`);
})
.catch(error => {
console.error('An error occurred during crawling:', error);
});
Explanation:
axios: Used to make HTTP GET requests to fetch the HTML content of pages.
cheerio: Parses the HTML response. It provides a familiar jQuery-like API ($) to traverse and manipulate the DOM of the received HTML.
$('.selector'): Selects elements.
$(element).attr('href'): Gets an attribute value.
$(element).text().trim(): Gets the text content.
$(element).closest('h1, h2'): Finds the nearest ancestor matching the selector.
URL (Node.js built-in): Essential for:
- Normalizing URLs (e.g., resolving
../page.html to an absolute URL).
- Checking
hostname to ensure you stay within the target website's domain and don't crawl the entire internet.
visitedUrls Set: Keeps track of all URLs that have already been processed to prevent infinite loops (e.g., A links to B, B links to A) and to avoid redundant processing.
urlsToVisit Queue: An array used as a queue (FIFO - First In, First Out) for URLs that still need to be crawled.
maxDepth: A crucial parameter to limit how deep the crawler goes. Without it, a crawler could run indefinitely on large websites.
- Error Handling: Basic
try...catch blocks are included for network errors or invalid URLs.
- Concurrency (Advanced): This simple crawler processes pages sequentially. For large-scale crawling, you'd want to implement concurrency (e.g., using
Promise.all with a limited number of parallel requests) to speed things up. Dedicated crawling libraries like puppeteer (for JS-rendered sites) or simplecrawler offer more advanced features like rate limiting, retries, and more robust error handling.
How to Run the Node.js Crawler:
- Save the code above as
crawler.js.
- Open your terminal or command prompt.
- Navigate to the directory where you saved
crawler.js.
- Run:
node crawler.js
- Observe the output in your console. The
websiteData array will be printed as a JSON string.
Important Considerations for Crawling:
robots.txt: Respect robots.txt rules of websites. This file tells crawlers which parts of a site they are allowed to access. A production-ready crawler would parse this file before making requests.
- Rate Limiting: Don't hit websites too hard or too fast. Make requests at a reasonable pace to avoid being blocked or overloading the server.
- Dynamic Content (JavaScript Rendering): If the website heavily relies on JavaScript to load content and links (e.g., Single Page Applications),
axios and cheerio won't execute JavaScript. For such sites, you'd need a "headless browser" like Puppeteer or Playwright.
- Legality and Ethics: Always check the website's terms of service. Unauthorized scraping can be illegal or against their policies. Be mindful of server load.