def download_all_pdfs():
# Iterate through all titles (1 to 74)
for title in range(1, 75):
# Assume a maximum of 70 chapters per title (adjust if needed)
for chapter in range(1, 50):
download_pdf(title, chapter)
import os
import requests
import time # Optional: for adding delays if needed
# 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 base output directory if it doesn't exist
os.makedirs(OUTPUT_DIR, exist_ok=True)
# Function to download a PDF
def download_pdf(title_str, chapter_str, title_output_dir):
"""
Downloads a single PDF chapter for a given title.
Args:
title_str (str): The title number, zero-padded to 2 digits (e.g., "01").
chapter_str (str): The chapter number, zero-padded to 2 digits (e.g., "01").
title_output_dir (str): The directory path where the PDF should be saved.
Returns:
bool: True if download was successful (status 200), False otherwise.
Specifically returns False on 404 to signal the end of chapters.
"""
url = f"{BASE_URL}Title{title_str}/T{title_str}CH{chapter_str}.pdf"
filename = os.path.join(title_output_dir, f"T{title_str}CH{chapter_str}.pdf")
# Optional: Skip if file already exists
# if os.path.exists(filename):
# print(f"Already exists: {filename}")
# return True
try:
# Added timeout (in seconds)
response = requests.get(url, timeout=15)
if response.status_code == 200:
# Save the PDF
with open(filename, "wb") as f:
f.write(response.content)
print(f"Downloaded: {filename}")
return True
elif response.status_code == 404:
print(f"Chapter not found (404): {url} - Assuming end of chapters for Title {title_str}.")
return False # Signal to stop trying chapters for this title
else:
# Handle other potential HTTP errors (e.g., 500, 403)
print(f"Failed to download {url} - Status Code: {response.status_code}")
return False # Treat other errors as failures, but maybe retry later? For now, stop.
except requests.exceptions.RequestException as e:
# Handle network errors (timeout, connection error, etc.)
print(f"Request Error downloading {url}: {e}")
return False # Signal failure
# Main function to download all PDFs adaptively
def download_all_pdfs_adaptive():
"""
Downloads all Idaho legal code PDFs, creating folders for each title
and adaptively finding the last chapter for each title.
"""
# Iterate through all titles (assuming 1 to 74)
for title in range(1, 75):
title_str = str(title).zfill(2) # Pad title number to 2 digits
title_dir = os.path.join(OUTPUT_DIR, f"Title{title_str}")
# Create the title-specific directory
os.makedirs(title_dir, exist_ok=True)
print(f"\n--- Processing Title {title_str} ---")
chapter = 1
while True: # Keep trying chapters until a 404 is encountered
chapter_str = str(chapter).zfill(2) # Pad chapter number to 2 digits
# Attempt to download the chapter PDF
success = download_pdf(title_str, chapter_str, title_dir)
if not success:
# If download failed (
import os
import requests
import time # Optional: for adding delays if needed
# Base URL for the Idaho Legal Code PDFs - This seems correct based on your example
BASE_URL = "https://legislature.idaho.gov/wp-content/uploads/statutesrules/idstat/"
# Directory to save the PDFs
OUTPUT_DIR = "idaho_legal_code"
# Create the base output directory if it doesn't exist
os.makedirs(OUTPUT_DIR, exist_ok=True)
# Function to download a PDF
def download_pdf(title_str_padded, chapter_num, title_output_dir):
"""
Downloads a single PDF chapter for a given title.
Args:
title_str_padded (str): The title number, zero-padded to 2 digits (e.g., "09", "74").
chapter_num (int): The chapter number (e.g., 1, 13).
title_output_dir (str): The directory path where the PDF should be saved.
Returns:
bool: True if download was successful (status 200), False otherwise.
Specifically returns False on 404 to signal the end of chapters.
"""
# Chapter number is NOT zero-padded in the URL/filename
chapter_str_unpadded = str(chapter_num)
# Construct the URL and Filename based on the observed pattern
# Example: https://legislature.idaho.gov/wp-content/uploads/statutesrules/idstat/Title74/T74CH1.pdf
url = f"{BASE_URL}Title{title_str_padded}/T{title_str_padded}CH{chapter_str_unpadded}.pdf"
filename = os.path.join(title_output_dir, f"T{title_str_padded}CH{chapter_str_unpadded}.pdf")
# Optional: Skip if file already exists
# if os.path.exists(filename):
# print(f"Skipping existing: {filename}")
# return True
print(f"Attempting: {url}") # Added for better feedback
try:
# Added timeout (in seconds)
response = requests.get(url, timeout=20) # Increased timeout slightly
if response.status_code == 200:
# Save the PDF
with open(filename, "wb") as f:
f.write(response.content)
print(f"Downloaded: {filename}")
return True
elif response.status_code == 404:
# This is the expected way to find the end of chapters for a title
print(f"Chapter not found (404): {url} - End of chapters for Title {title_str_padded}.")
return False # Signal to stop trying chapters for this title
else:
# Handle other potential HTTP errors (e.g., 500, 403)
print(f"Failed download attempt for {url} - Status Code: {response.status_code}")
return False # Treat other errors as failures, stop trying chapters for this title for now.
except requests.exceptions.Timeout:
print(f"Request Timed Out for {url}")
return False # Signal failure, stop trying chapters for this title
except requests.exceptions.RequestException as e:
# Handle other network errors (connection error, etc.)
print(f"Request Error downloading {url}: {e}")
return False # Signal failure, stop trying chapters for this title
# Main function to download all PDFs adaptively
def download_all_pdfs_adaptive():
"""
Downloads all Idaho legal code PDFs, creating folders for each title
and adaptively finding the last chapter for each title.
"""
# Iterate through all titles (assuming 1 to 74 based on example)
# Adjust range if necessary
for title in range(1, 75):
title_str_padded = str(title).zfill(2) # Pad title number to 2 digits (e.g., "01", "74")
title_dir = os.path.join(OUTPUT_DIR, f"Title{title_str_padded}")
# Create the title-specific directory
os.makedirs(title_dir, exist_ok=True)
print(f"\n--- Processing Title {title_str_padded} ---")
chapter = 1
consecutive_failures = 0 # Count failures other than 404
max_consecutive_failures = 3 # Stop if we get too many non-404 errors
while True: # Keep trying chapters until a 404 or too many errors
# Attempt to download the chapter PDF
success = download_pdf(title_str_padded, chapter, title_dir)
if success:
consecutive_failures = 0 # Reset failure count on success
chapter += 1
# Optional: Add a small delay to be polite to the server
# time.sleep(0.1)
else:
# Check the status code from the download attempt (implicitly via return value)
# If download_pdf returned False because of 404, it printed the message already.
# We break the inner loop ONLY on 404 (or other conditions below).
# We need to check if the failure was a 404 or something else.
# Re-check the URL status to be certain (though slightly redundant)
check_url = f"{BASE_URL}Title{title_str_padded}/T{title_str_padded}CH{str(chapter)}.pdf"
try:
# Use HEAD request which is faster as it doesn't download the body
head_response = requests.head(check_url, timeout=5)
if head_response.status_code == 404:
# It was definitely a 404, expected end, break inner loop
print(f"Confirmed end of chapters for Title {title_str_padded} at Chapter {chapter}.")
break
else:
# It was a different error (timeout, connection, other HTTP status)
print(f"Non-404 failure for Chapter {chapter} (Status: {head_response.status_code if hasattr(head_response, 'status_code') else 'N/A'}). Retrying or stopping.")
consecutive_failures += 1
except requests.exceptions.RequestException:
# Network error during the HEAD check
print(f"Network error during HEAD check for Chapter {chapter}. Retrying or stopping.")
consecutive_failures += 1
if consecutive_failures >= max_consecutive_failures:
print(f"Stopping Title {title_str_padded} after {max_consecutive_failures} consecutive non-404 failures.")
break # Stop trying chapters for this title due to repeated errors
# Optional: Decide whether to increment chapter or retry the same one on non-404 error
# Incrementing might skip a temporarily unavailable chapter.
# Retrying might get stuck. Let's increment for now.
print(f"Trying next chapter ({chapter + 1}) after non-404 failure on chapter {chapter}.")
chapter += 1
# Consider adding a longer delay after errors
# time.sleep(1)
if __name__ == "__main__":
download_all_pdfs_adaptive()
print("\n--- Download process completed ---")