Below is a complete, self-contained implementation of a fast and efficient web spider in Google Colab. This script uses Python's standard libraries along with requests for HTTP requests and BeautifulSoup for HTML parsing. It prioritizes URLs from new subdomains and domains in its queue, as per your requirements.
Key Features:
- Prioritization: The spider uses a priority queue. URLs from new subdomains/domains (based on the hostname, e.g.,
sub.example.com) are added with high priority (priority level 1). All other URLs are added with low priority (priority level 2).
- Efficiency:
- It avoids revisiting pages using a set.
- Includes a delay between requests to respect website policies and avoid IP blocking.
- Limits the crawl to a maximum number of pages (e.g., 100) to prevent runtime issues in Colab.
- Handles basic error checking and only processes HTTP/HTTPS links.
- Output: Every page found (i.e., successfully fetched) is appended to the file at
PAGES_FILE = "/content/drive/MyDrive/Colab Notebooks/Archive Scraper/pages.txt". Each line in the file will contain a URL.
- Seed URL: I've hardcoded a seed URL (
http://example.com) for simplicity. You can modify it as needed.
- Colab-Specific Setup: The script mounts Google Drive and handles file I/O.
How to Run:
- Open Google Colab and create a new notebook.
- Install the required libraries by running the first cell (it includes
!pip install commands).
- Run the full script in a subsequent cell.
- Ensure your Google Drive is accessible and the path exists. If not, create the file manually or let the script create it.
- Be aware of Colab's runtime limits (e.g., 12 hours max). This script is designed to stop after 100 pages or when the queue is empty.
Potential Improvements:
- Rate Limiting: I've added a 1-second delay per request. You can adjust this.
- Advanced Features: For production, add support for
robots.txt or use asynchronous requests for speed.
- Error Handling: It catches basic exceptions, but you might want to log more details.
Here's the code:
# Install required libraries
!pip install requests beautifulsoup4
import requests
from bs4 import BeautifulSoup
import urllib.parse
import queue # For PriorityQueue
import time
from google.colab import drive
# Mount Google Drive
drive.mount('/content/drive')
# Define constants
PAGES_FILE = "/content/drive/MyDrive/Colab Notebooks/Archive Scraper/pages.txt"
SEED_URL = "http://example.com" # Starting point; change as needed
MAX_PAGES = 100 # Limit to prevent infinite loops and runtime issues
DELAY_SECONDS = 1 # Polite delay between requests
# Initialize data structures
pq = queue.PriorityQueue() # Priority queue: (priority, URL)
visited = set() # Set to track visited URLs
seen_hostnames = set() # Set to track seen hostnames for prioritization
def get_hostname(url):
"""Extract the hostname (e.g., subdomain.domain.com) from a URL."""
parsed = urllib.parse.urlparse(url)
return parsed.netloc
# Add seed URL to the queue with high priority
seed_hostname = get_hostname(SEED_URL)
seen_hostnames.add(seed_hostname) # Mark as seen
pq.put((1, SEED_URL)) # Priority 1 for new hostnames
def crawl():
counter = 0 # Track the number of pages processed
while not pq.empty() and counter < MAX_PAGES:
priority, current_url = pq.get() # Get the next item (priority, URL)
if current_url not in visited:
visited.add(current_url) # Mark as visited
try:
headers = {'User-Agent': 'MyColabSpiderBot/1.0'} # Set a user-agent to mimic a browser
response = requests.get(current_url, headers=headers, timeout=10) # 10-second timeout
if response.status_code == 200:
# Write the URL to the file
with open(PAGES_FILE, 'a') as f:
f.write(current_url + '\n') # Append the URL
print(f"Processed: {current_url} (Page {counter+1}/{MAX_PAGES})")
# Parse the page and extract links
soup = BeautifulSoup(response.text, 'html.parser')
links = soup.find_all('a', href=True)
for link in links:
abs_link = urllib.parse.urljoin(current_url, link['href']) # Resolve relative URLs
parsed_link = urllib.parse.urlparse(abs_link)
# Only process HTTP/HTTPS links
if parsed_link.scheme in ['http', 'https']:
link_hostname = parsed_link.netloc # e.g., 'sub.example.com'
if link_hostname not in seen_hostnames:
# New subdomain/domain: High priority (1)
pq.put((1, abs_link)) # Add with high priority
seen_hostnames.add(link_hostname) # Mark as seen
else:
# Existing subdomain/domain: Low priority (2)
pq.put((2, abs_link)) # Add with low priority
counter += 1 # Increment page counter
time.sleep(DELAY_SECONDS) # Delay to be polite
else:
print(f"Skipped {current_url} (Status code: {response.status_code})")
except Exception as e:
print(f"Error processing {current_url}: {e}")
# Start the crawl
print("Starting web spider...")
crawl()
print("Crawling complete. Check pages.txt for the list of pages.")
Explanation of the Code:
-
Imports and Setup:
- Installs and imports necessary libraries.
- Mounts Google Drive to access the file path.
-
Queue Management:
pq is a PriorityQueue where items are tuples: (priority, URL).
- Priority 1 (high) is for URLs from new hostnames.
- Priority 2 (low) is for URLs from already-seen hostnames.
- The queue ensures that high-priority items are processed first.
-
Hostname Tracking:
seen_hostnames set keeps track of unique hostnames (e.g., www.example.com, sub.example.com).
- When a new hostname is detected during link extraction, its URL is added with high priority, and the hostname is added to the set.
-
Crawling Loop:
- Dequeues URLs and processes them if not visited.
- Fetches the page, extracts links, and enqueues them with appropriate priorities.
- Appends each successfully fetched URL to
pages.txt.
- Stops after
MAX_PAGES or when the queue is empty.
-
File Handling:
- The file is opened in append mode (
'a') each time a URL is written, ensuring it doesn't overwrite existing content.
- If the file doesn't exist, it will be created automatically.
Output and Monitoring:
- During execution, the script prints messages like
Processed: http://example.com (Page 1/100).
- After running, check the file at
/content/drive/MyDrive/Colab Notebooks/Archive Scraper/pages.txt. It will contain one URL per line for every page successfully crawled.
- To monitor progress, you can add more print statements or use Colab's output logs.
Limitations and Tips:
- Runtime in Colab: If your crawl is large, it might hit Colab's limits. Start with a small
MAX_PAGES (e.g., 10) for testing.
- Legal Considerations: Web scraping should respect website terms and robots.txt. This script doesn't check robots.txt—consider adding it if needed.
- Testing: Replace the seed URL with your target (e.g., "http://yourwebsite.com") and test on a small site.
- Enhancements: If you need to handle more edge cases (e.g., URL normalization, duplicate detection), let me know for updates.
This should get you started! If you encounter issues or need modifications, provide more details.