It appears that the Download buttons on the eGazette website don't initiate a direct download of the PDFs. Instead, they open a new window or tab where the PDF is displayed using the browser's built-in PDF viewer. This behavior can interfere with automatic downloading via Selenium, especially if the website relies on JavaScript to render the PDF or uses dynamic URLs.
Here's what's happening:
- When you click the
Download button, it opens a new page or tab displaying the PDF.
- Your Chrome preferences aim to force PDFs to download immediately, but due to how the site serves the PDFs, these settings aren't taking effect.
- Selenium doesn't automatically handle downloads initiated in new windows or tabs unless you explicitly manage these windows.
Solution:
To resolve this issue, you can modify your script to:
- Handle the new window or tab that opens upon clicking the download button.
- Extract the direct URL of the PDF file from the new window.
- Use that URL to download the PDF using the
requests library.
Alternatively, you can capture network requests to find the direct URL of the PDF and then download it. Below, I'll provide a step-by-step guide for both methods.
Method 1: Handle the New Window and Download the PDF
Step 1: Click the Download Button and Switch to the New Window
After clicking the download button, your script should detect the new window and switch focus to it.
# Click the download button
download_button.click()
print(f"Clicked to download gazette number {i + 1}")
# Wait for the new window to open
WebDriverWait(driver, 10).until(EC.number_of_windows_to_be(2))
# Get window handles and switch to the new window
windows = driver.window_handles
driver.switch_to.window(windows[1])
Step 2: Extract the PDF URL
Once you're in the new window, you can extract the URL of the PDF.
pdf_url = driver.current_url
print(f"PDF URL: {pdf_url}")
Step 3: Download the PDF Using requests
Use the requests library to download the PDF directly.
import requests
response = requests.get(pdf_url)
if response.status_code == 200:
pdf_file_path = f'F:/Lamarr/egazette/docs/gazette_{i+1}.pdf'
with open(pdf_file_path, 'wb') as f:
f.write(response.content)
print(f"PDF downloaded and saved to {pdf_file_path}")
else:
print(f"Failed to download PDF: HTTP {response.status_code}")
Step 4: Close the New Window and Switch Back
After downloading, close the new window and switch back to the main window.
driver.close() # Close the new window
driver.switch_to.window(windows[0]) # Switch back to the main window
Full Modified Code Sample:
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
import time
import requests
# Your existing setup code...
options = webdriver.ChromeOptions()
options.add_experimental_option('prefs', {
"download.default_directory": "F:/Lamarr/egazette/docs",
"download.prompt_for_download": False,
"download.directory_upgrade": True,
"safebrowsing.enabled": True,
"plugins.always_open_pdf_externally": True,
})
driver = webdriver.Chrome(options=options)
driver.get(url)
driver.maximize_window()
driver.implicitly_wait(10)
# Your existing navigation code...
try:
for i in range(7):
try:
download_button_xpath = f'//*[@id="gvGazetteList_imgbtndownload_{i}"]'
download_button = driver.find_element(By.XPATH, download_button_xpath)
download_button.click()
print(f"Clicked to download gazette number {i + 1}")
# Wait for the new window
WebDriverWait(driver, 10).until(EC.number_of_windows_to_be(2))
windows = driver.window_handles
driver.switch_to.window(windows[1]) # Switch to the new window
# Extract PDF URL
pdf_url = driver.current_url
print(f"PDF URL: {pdf_url}")
# Download the PDF
response = requests.get(pdf_url)
if response.status_code == 200:
pdf_file_path = f'F:/Lamarr/egazette/docs/gazette_{i+1}.pdf'
with open(pdf_file_path, 'wb') as f:
f.write(response.content)
print(f"PDF downloaded and saved to {pdf_file_path}")
else:
print(f"Failed to download PDF: HTTP {response.status_code}")
# Close the new window and switch back
driver.close()
driver.switch_to.window(windows[0])
except Exception as download_exception:
print(f"Error downloading gazette number {i + 1}: {download_exception}")
except Exception as e:
print(f"An error occurred: {e}")
print("Download process completed.")
Method 2: Capture Network Requests to Find the PDF URL
You can use selenium-wire, a library that extends Selenium's capabilities to capture network requests. This method is effective if the PDF URL isn't directly accessible from the new window's URL bar.
Step 1: Install selenium-wire
pip install selenium-wire
Step 2: Modify Your Imports
from seleniumwire import webdriver # Note the change here
Step 3: Update Your Code to Use selenium-wire
Before clicking the download button, clear previous requests and set up selenium-wire to capture requests.
# Your existing setup code...
from seleniumwire import webdriver
driver = webdriver.Chrome(options=options)
# ...
# Before clicking the download button, clear previous requests
driver.scopes = ['.*'] # Capture all requests
driver.requests.clear()
for i in range(7):
try:
# Click the download button
download_button_xpath = f'//*[@id="gvGazetteList_imgbtndownload_{i}"]'
download_button = driver.find_element(By.XPATH, download_button_xpath)
download_button.click()
print(f"Clicked to download gazette number {i + 1}")
time.sleep(3)
# Inspect requests to find the PDF URL
for request in driver.requests:
if request.response and 'application/pdf' in request.response.headers.get('Content-Type', ''):
pdf_url = request.url
print(f"Found PDF URL: {pdf_url}")
# Download the PDF
response = requests.get(pdf_url)
if response.status_code == 200:
pdf_file_path = f'F:/Lamarr/egazette/docs/gazette_{i+1}.pdf'
with open(pdf_file_path, 'wb') as f:
f.write(response.content)
print(f"PDF downloaded and saved to {pdf_file_path}")
else:
print(f"Failed to download PDF: HTTP {response.status_code}")
# Clear requests after processing
driver.requests.clear()
except Exception as download_exception:
print(f"Error downloading gazette number {i + 1}: {download_exception}")
Additional Tips:
- Avoid Disabling Plugins Unnecessarily: The preference
"plugins.plugins_disabled": ["Chrome PDF Viewer"] might conflict with other settings. Consider removing it.
- Make Sure to Wait for Elements and Windows: Use explicit waits like
WebDriverWait instead of time.sleep() to handle dynamic content more reliably.
- Check for JavaScript-Generated Content: If the PDF is generated via JavaScript (e.g., using
Blob URLs), you might need a different approach, such as using a headless browser or analyzing the JavaScript code.
Understanding What Happened:
Your original settings didn't work because:
- The site doesn't provide direct links to PDFs; it opens them in a viewer.
- Browser settings can't force-download PDFs when they're opened in a viewer via JavaScript.
- Selenium doesn't automatically interact with new windows or tabs.
By extracting the PDF URL from the new window or the network requests, you bypass the need to interact with the browser's download mechanisms and directly save the files.
Conclusion:
Automating downloads from websites that use dynamic content can be challenging. By handling new windows and capturing network requests, you can effectively download PDFs or other resources even when they're not directly linked in the page's HTML.
Let me know if you need further assistance or have any questions!