Certainly! Below is a robust Python script that uses the Scrapy framework to download documentation from websites like the ones you provided. This script is designed to handle errors gracefully, respect the site's crawling policies, and save the content in an organized manner.
Please follow the instructions carefully to ensure the script runs smoothly.
# Save this script as download_docs.py
import scrapy
from scrapy.crawler import CrawlerProcess
from scrapy.spiders import CrawlSpider, Rule
from scrapy.linkextractors import LinkExtractor
import os
from urllib.parse import urlparse, urljoin
import logging
class DocDownloaderSpider(CrawlSpider):
name = "doc_downloader"
def __init__(self, start_url=None, *args, **kwargs):
super(DocDownloaderSpider, self).__init__(*args, **kwargs)
if start_url:
self.start_urls = [start_url]
parsed_uri = urlparse(start_url)
self.allowed_domains = [parsed_uri.netloc]
# Define rules to follow links within the domain
self.rules = (
Rule(
LinkExtractor(
allow_domains=self.allowed_domains,
deny_extensions=['js', 'css', 'png', 'jpg', 'jpeg', 'gif', 'svg', 'ico', 'json']
),
callback='parse_item',
follow=True
),
)
super(DocDownloaderSpider, self)._compile_rules()
else:
raise ValueError("start_url must be provided")
def parse_item(self, response):
# Handle non-HTML content types
content_type = response.headers.get('Content-Type', b'').decode('utf-8')
if 'text/html' not in content_type:
return
# Create directories based on URL path
url_path = urlparse(response.url).path
if not url_path or url_path.endswith('/'):
url_path = os.path.join(url_path, 'index.html')
elif not os.path.splitext(url_path)[1]:
url_path = url_path + '.html'
# Construct the file path
file_path = os.path.join("downloaded_docs", *url_path.strip("/").split("/"))
# Ensure directory exists
os.makedirs(os.path.dirname(file_path), exist_ok=True)
# Save response body to file
try:
with open(file_path, 'wb') as f:
f.write(response.body)
self.logger.info(f"Saved {response.url} to {file_path}")
except Exception as e:
self.logger.error(f"Error saving {response.url} to {file_path}: {e}")
if __name__ == '__main__':
import sys
if len(sys.argv) < 2:
print("Usage: python download_docs.py <start_url>")
sys.exit(1)
start_url = sys.argv[1]
# Set up logging
logging.basicConfig(
filename='download_docs.log',
format='%(asctime)s - %(levelname)s: %(message)s',
level=logging.INFO
)
logging.getLogger('scrapy').setLevel(logging.WARNING)
process = CrawlerProcess({
'USER_AGENT': 'doc_downloader (+http://example.com)',
'AUTOTHROTTLE_ENABLED': True,
'AUTOTHROTTLE_START_DELAY': 1,
'AUTOTHROTTLE_MAX_DELAY': 10,
'LOG_LEVEL': 'INFO',
'ROBOTSTXT_OBEY': True,
'HTTPCACHE_ENABLED': True,
'CONCURRENT_REQUESTS_PER_DOMAIN': 8,
})
process.crawl(DocDownloaderSpider, start_url=start_url)
process.start()
Instructions to Run the Script:
-
Install Scrapy: If you haven't installed Scrapy yet, you can install it using pip:
pip install scrapy
-
Save the Script: Save the script above in a file named download_docs.py.
-
Run the Script: Open your terminal or command prompt, navigate to the directory containing download_docs.py, and run:
python download_docs.py https://docs.zrok.io/docs
or
python download_docs.py https://python.langchain.com/v0.2/docs
-
Wait for Completion: The script will begin crawling the specified documentation site and downloading the HTML pages. It respects robots.txt rules and is designed to be polite by not overwhelming the server.
-
Check the Output: The downloaded documentation will be saved in the downloaded_docs directory, maintaining the site's directory structure.
Features of the Script:
- Error Handling: The script logs errors and skips non-HTML content types to avoid saving unnecessary files.
- Polite Crawling: Respects
robots.txt and uses Scrapy's AutoThrottle to adjust crawling speed based on the site's response.
- Link Extraction: Uses
LinkExtractor to find and follow links within the allowed domain, avoiding external links and certain file types.
- Organized Output: Saves files in a directory structure that mirrors the site's URL paths.
- Logging: Logs important information and errors to
download_docs.log for later review.
Important Notes:
- Respect Website Policies: Always make sure to respect the website's crawling policies as specified in their
robots.txt file. This script is set to obey these rules by default (ROBOTSTXT_OBEY = True).
- Bandwidth Usage: Downloading entire websites can consume significant bandwidth. Ensure you have permission and resources to do so.
- Modify as Needed: You can adjust settings like
CONCURRENT_REQUESTS_PER_DOMAIN, AUTOTHROTTLE_START_DELAY, and others in the CrawlerProcess configuration to optimize performance based on your needs.
Testing with the Provided URLs:
You can test the script using the URLs you've provided:
python download_docs.py https://docs.zrok.io/docs
python download_docs.py https://python.langchain.com/v0.2/docs
The script will create a downloaded_docs folder in the current directory with all the downloaded pages.
Feel free to let me know if you have any questions or need further assistance!