Apologies for the earlier confusion regarding the URLs. Based on your clarification, the correct base URL for the Idaho Statutes PDFs is:
https://legislature.idaho.gov/wp-content/uploads/statutesrules/idstat/
To adapt your script accordingly and ensure it downloads the PDFs correctly, please use the following updated version:
import os
import requests
from concurrent.futures import ThreadPoolExecutor
# Base URL for the Idaho Legal Code PDFs
BASE_URL = "https://legislature.idaho.gov/wp-content/uploads/statutesrules/idstat/"
# Directory to save the PDFs
OUTPUT_DIR = "idaho_legal_code"
# Create the output directory if it doesn't exist
os.makedirs(OUTPUT_DIR, exist_ok=True)
# Function to get the number of chapters for a given title
def get_num_chapters(title):
url = f"{BASE_URL}Title{str(title).zfill(2)}/"
response = requests.get(url)
if response.status_code == 200:
# Parse the HTML to find the number of chapters
# This is a simplified approach; consider using an HTML parser like BeautifulSoup for robustness
content = response.text
start_index = content.find('CHAPTER')
if start_index != -1:
chapters = content[start_index:].split('CHAPTER')[1:]
return len(chapters)
return 0
# Function to download a PDF
def download_pdf(title, chapter):
url = f"{BASE_URL}Title{str(title).zfill(2)}/T{str(title).zfill(2)}CH{str(chapter).zfill(2)}.pdf"
response = requests.get(url)
if response.status_code == 200:
# Create a directory for the title if it doesn't exist
title_dir = os.path.join(OUTPUT_DIR, f"Title{str(title).zfill(2)}")
os.makedirs(title_dir, exist_ok=True)
# Save the PDF to the title directory
filename = os.path.join(title_dir, f"Title{str(title).zfill(2)}_Chapter{str(chapter).zfill(2)}.pdf")
with open(filename, "wb") as f:
f.write(response.content)
print(f"Downloaded: {filename}")
else:
print(f"Failed to download: {url}")
# Main function to download all PDFs
def download_all_pdfs():
# Iterate through all titles (1 to 74)
for title in range(1, 75):
num_chapters = get_num_chapters(title)
if num_chapters > 0:
# Use ThreadPoolExecutor to download chapters concurrently
with ThreadPoolExecutor(max_workers=5) as executor:
for chapter in range(1, num_chapters + 1):
executor.submit(download_pdf, title, chapter)
if __name__ == "__main__":
download_all_pdfs()
Key Updates:
-
Correct Base URL: The script now uses the correct base URL for the Idaho Statutes PDFs: https://legislature.idaho.gov/wp-content/uploads/statutesrules/idstat/.
-
Dynamic Chapter Count: The get_num_chapters function retrieves the number of chapters for each title by parsing the HTML content of the title's webpage. This approach ensures the script adapts to the actual number of chapters available.