LeetCode Problem 1242: Multi-Threaded Web Crawler
The goal is to implement a web crawler that starts from a given URL, fetches the HTML content, and extracts all the hyperlinks to other pages. The crawler should be multi-threaded to improve efficiency.
Solution Approach
We'll use Python's threading module to achieve multi-threading. Each thread will be responsible for fetching the HTML content of a URL and extracting hyperlinks. We'll use a queue to manage the URLs to be crawled and a set to keep track of visited URLs to avoid duplicates.
Python Solution
from threading import Thread, Lock
from queue import Queue
from urllib.parse import urljoin
import requests
from bs4 import BeautifulSoup
class HtmlParser:
def __init__(self):
self.visited = set()
self.urls_to_crawl = Queue()
self.lock = Lock()
self.result = []
def parse(self, url, html):
"""
Parse the HTML content and extract hyperlinks.
Args:
url (str): The current URL being processed.
html (str): The HTML content of the current URL.
Returns:
list: A list of extracted hyperlinks.
"""
soup = BeautifulSoup(html, 'html.parser')
base_url = '{}://{}'.format(url.split(':')[0], url.split(':')[1].split('/')[0])
links = set()
for link in soup.find_all('a', href=True):
href = link['href']
if href.startswith('/'):
href = urljoin(base_url, href)
elif not href.startswith('http'):
href = urljoin(url, href)
links.add(href)
return list(links)
def crawl(self, url):
"""
Crawl a single URL and extract hyperlinks.
Args:
url (str): The URL to crawl.
"""
try:
response = requests.get(url)
response.raise_for_status() # Raise an exception for HTTP errors
links = self.parse(url, response.text)
with self.lock:
self.result.extend([link for link in links if link not in self.visited])
self.visited.update(links)
for link in links:
if link not in self.visited:
self.urls_to_crawl.put(link)
except requests.exceptions.RequestException as e:
print(f"Error crawling {url}: {e}")
def worker(self):
"""
Worker function for each thread.
"""
while not self.urls_to_crawl.empty():
url = self.urls_to_crawl.get()
if url not in self.visited:
self.crawl(url)
with self.lock:
self.visited.add(url)
def multicrawl(self, urls, max_threads=10):
"""
Start the multi-threaded crawler.
Args:
urls (list): The list of seed URLs to start crawling from.
max_threads (int): The maximum number of threads to use.
Returns:
list: A list of all unique URLs crawled.
"""
for url in urls:
self.urls_to_crawl.put(url)
threads = []
for _ in range(min(max_threads, self.urls_to_crawl.qsize())):
thread = Thread(target=self.worker)
thread.start()
threads.append(thread)
for thread in threads:
thread.join()
return self.result
# Example usage:
# parser = HtmlParser()
# result = parser.multicrawl(['http://example.com'])
# print(result)
Explanation
- We define an
HtmlParser class that encapsulates the crawling logic.
- The
parse method uses BeautifulSoup to extract hyperlinks from the HTML content.
- The
crawl method fetches the HTML content of a URL, extracts hyperlinks, and adds them to the queue for further crawling.
- The
worker method is the target function for each thread, which continuously crawls URLs from the queue.
- The
multicrawl method starts the multi-threaded crawler, creating a specified number of threads to crawl the initial URLs and their hyperlinks.
Note: This solution assumes that the requests and beautifulsoup4 libraries are installed. You can install them using pip:
pip install requests beautifulsoup4
Also, be mindful of the website's robots.txt file and respect the website's crawling policies to avoid overloading their servers.