You're asking for a robust crawling system that:
✅ Avoids re-crawling URLs that were already successfully crawled
❌ Skips URLs that previously failed (optionally retries them later)
📄 Keeps two log files:
crawled.json – contains URLs that were successfully scraped
failed_urls.json – contains URLs that failed after all retries
We'll implement this in the optimized script using:
- A set of already crawled URLs loaded from
crawled.json
- Append new URLs to
crawled.json as they complete
- Maintain and update
failed_urls.json accordingly
✅ Final Script: Full Windows-Compatible, Retry-Safe Crawler with History Tracking
📁 File Outputs
output/urls_batch_0.json, output/urls_batch_1.json, ... → Article HTML content
crawled.json → List of successfully crawled URLs
failed_urls.json → List of URLs that failed after all retries
🐍 crawler_with_history.py
import sqlite3
import os
import json
import time
import requests
from concurrent.futures import ThreadPoolExecutor, as_completed
from bs4 import BeautifulSoup
from urllib.parse import urljoin
# ================= CONFIGURATION =================
DB_PATH = 'your_database.db'
MAIN_LINK_TABLE = 'main_link'
OUTPUT_DIR = 'output'
CRAWLED_FILE = 'crawled.json'
FAILED_URLS_FILE = 'failed_urls.json'
TAGS_FILE = 'tags.json'
USER_AGENT = 'Mozilla/5.0 (compatible; ArticleCrawler/1.0)'
MAX_THREADS = 20
BATCH_SIZE = 1000
REQUEST_TIMEOUT = 10
RETRY_LIMIT = 3
DELAY_BETWEEN_REQUESTS = 0.1
# =================================================
os.makedirs(OUTPUT_DIR, exist_ok=True)
session = requests.Session()
session.headers.update({'User-Agent': USER_AGENT})
# Global data containers
results = []
all_tags = []
failed_urls = set()
crawled_urls = set()
ILLEGAL_WIN_CHARS = r'\/:*?"<>|'
REPLACE_CHAR = '_'
WINDOWS_RESERVED_NAMES = {
"CON", "PRN", "AUX", "NUL",
"COM1", "COM2", "COM3", "COM4", "COM5", "COM6", "COM7", "COM8", "COM9",
"LPT1", "LPT2", "LPT3", "LPT4", "LPT5", "LPT6", "LPT7", "LPT8", "LPT9"
}
def sanitize_filename(name):
"""Convert URL or string to a Windows-safe filename."""
# Replace illegal characters
for char in ILLEGAL_WIN_CHARS:
name = name.replace(char, REPLACE_CHAR)
# Ensure no leading/trailing spaces or periods
name = name.strip().strip('.')
# Check for reserved names
if name.upper() in WINDOWS_RESERVED_NAMES:
name += "_file"
# Limit to 255 characters
if len(name) > 255:
name = name[:255]
return name
def load_crawled_urls():
"""Load previously crawled URLs to avoid reprocessing."""
if os.path.exists(CRAWLED_FILE):
try:
with open(CRAWLED_FILE, 'r', encoding='utf-8') as f:
return set(json.load(f))
except json.JSONDecodeError:
print("[INFO] Crawled file is corrupt or empty.")
return set()
return set()
def save_crawled_urls(urls):
"""Save list of successfully crawled URLs."""
with open(CRAWLED_FILE, 'w', encoding='utf-8') as f:
json.dump(list(urls), f, indent=2, ensure_ascii=False)
print(f"Saved {len(urls)} crawled URLs to {CRAWLED_FILE}")
def get_urls_from_sqlite():
conn = sqlite3.connect(DB_PATH)
cursor = conn.cursor()
cursor.execute(f"SELECT url FROM {MAIN_LINK_TABLE}")
urls = [row[0] for row in cursor.fetchall()]
conn.close()
return urls
def load_failed_urls():
if os.path.exists(FAILED_URLS_FILE):
try:
with open(FAILED_URLS_FILE, 'r', encoding='utf-8') as f:
return set(json.load(f))
except json.JSONDecodeError:
print("[INFO] Failed URLs file is corrupt or empty.")
return set()
return set()
def save_failed_urls(urls):
with open(FAILED_URLS_FILE, 'w', encoding='utf-8') as f:
json.dump(list(urls), f, indent=2, ensure_ascii=False)
print(f"Saved {len(urls)} failed URLs to {FAILED_URLS_FILE}")
def fetch_page(url):
retries = 0
while retries < RETRY_LIMIT:
try:
time.sleep(DELAY_BETWEEN_REQUESTS)
response = session.get(url, timeout=REQUEST_TIMEOUT)
response.raise_for_status()
return url, response.text
except Exception as e:
print(f"[ERROR] Failed to fetch {url} (attempt {retries + 1}/{RETRY_LIMIT}): {e}")
retries += 1
time.sleep(2 ** retries) # Exponential backoff
return url, None
def extract_content(url, html):
if not html:
failed_urls.add(url)
return None
soup = BeautifulSoup(html, 'lxml')
body_elem = soup.select_one('.article_body')
comments_elem = soup.select_one('.comment_list')
body_html = str(body_elem) if body_elem else None
comments_html = str(comments_elem) if comments_elem else None
# Extract tags
links = soup.select('.keywords a')
base = '/'.join(url.split('/')[:3]) # scheme + domain
for a in links:
href = a.get('href')
text = a.get_text(strip=True)
if href:
full_url = urljoin(base, href)
all_tags.append({
"link": full_url,
"anchor": text
})
crawled_urls.add(url)
return {
"url": url,
"body": body_html,
"comments": comments_html
}
def save_batch(batch, batch_num):
filename_base = f"urls_batch_{batch_num}"
safe_filename = sanitize_filename(filename_base)
filename = f"{safe_filename}.json"
filepath = os.path.join(OUTPUT_DIR, filename)
with open(filepath, 'w', encoding='utf-8') as f:
json.dump(batch, f, indent=2, ensure_ascii=False)
print(f"Saved batch {batch_num} to {filepath}")
def save_tags():
if not all_tags:
return
safe_file = sanitize_filename(TAGS_FILE)
with open(safe_file, 'w', encoding='utf-8') as f:
json.dump(all_tags, f, indent=2, ensure_ascii=False)
print(f"Saved {len(all_tags)} tags to {safe_file}")
def process_batch(urls, batch_num):
global results
futures = []
with ThreadPoolExecutor(max_workers=MAX_THREADS) as executor:
for url in urls:
if url in crawled_urls or url in failed_urls:
continue
futures.append(executor.submit(fetch_and_extract, url))
for future in as_completed(futures):
result = future.result()
if result:
results.append(result)
if results:
save_batch(results, batch_num)
save_crawled_urls(crawled_urls)
save_tags()
save_failed_urls(failed_urls)
results.clear()
def fetch_and_extract(url):
url, html = fetch_page(url)
return extract_content(url, html)
def main(retry_failed=False):
if retry_failed:
urls = list(load_failed_urls())
print(f"\n🔁 Retrying {len(urls)} failed URLs...")
else:
urls = get_urls_from_sqlite()
print(f"Found {len(urls)} URLs to process.")
total = len(urls)
batch_num = 0
for i in range(0, total, BATCH_SIZE):
print(f"\nProcessing batch {batch_num + 1} ({i + 1}–{min(i + BATCH_SIZE, total)})")
process_batch(urls[i:i + BATCH_SIZE], batch_num)
batch_num += 1
if __name__ == '__main__':
start_time = time.time()
crawled_urls = load_crawled_urls()
failed_urls = load_failed_urls()
print("🚀 Starting initial crawl...")
main(retry_failed=False)
print("\n🔄 Checking for failed URLs...")
if os.path.exists(FAILED_URLS_FILE):
with open(FAILED_URLS_FILE, 'r', encoding='utf-8') as f:
failed = json.load(f)
if failed:
print(f"\n🔁 Retrying {len(failed)} failed URLs...")
main(retry_failed=True)
print(f"\n✅ Done in {time.time() - start_time:.2f} seconds.")