Sure, here's an example Python code to scrape all the pages of a URL and save them to disk with the same file structure:
import requests
import os
# Define the URL to scrape
url = 'https://www.example.com'
# Set the base directory to save the scraped pages to
base_dir = '/path/to/save/'
# Set the maximum number of pages to scrape
max_pages = 10
# Loop through the pages, up to the maximum number of pages
for i in range(1, max_pages + 1):
# Construct the URL for the current page
url = url + f'?page={i}'
# Send a GET request to the URL and retrieve the HTML content
response = requests.get(url)
# Check if the page exists
if response.status_code == 200:
# Save the HTML content to a file with the same structure as the original page
file_name = os.path.join(base_dir, f'page_{i}.html')
with open(file_name, 'w') as f:
f.write(response.text)
print(f'Page {i} saved to {file_name}')
else:
print(f'Page {i} not found')
Here's how the code works:
- First, we define the URL to scrape and the base directory where we want to save the scraped pages.
- We then set the maximum number of pages to scrape and create a loop to iterate through the pages.
- For each page, we construct the URL by adding the
?page= parameter to the original URL, with the page number as the value of the parameter.
- We send a GET request to the URL using the
requests library and retrieve the HTML content of the page.
- We then save the HTML content to a file with the same structure as the original page, using the
os library to join the file name with the base directory and the page number.
- We print a message to indicate which page was saved.
- If the page does not exist, we print a message to indicate that the page was not found.
Note that this code assumes that the HTML content of each page is the same, except for the page= parameter in the URL. If the HTML content varies between pages, you may need to modify the code to extract the relevant information and save it to the file in the correct format.