I'm using Selenium to download several pdfs. To access the pdfs I use the .get() method of the WebDriver and instead of opening the preview I download the pdf directly through FirefoxProfile settings. However, WebDriver get always stucked and the rest of the code isn't executed anymore. I think it's because the WebDriver expects a new page to load and waits.
My workaround is that I set the pageLoadTimeout of the WebDriver and throw an TimeoutException. As I need to do this for each file, I was wondering wether there might be a more elegant way without throwing the TimeoutException.
An example code:
import org.openqa.selenium.TimeoutException;import org.openqa.selenium.WebDriver;import org.openqa.selenium.firefox.FirefoxDriver;import org.openqa.selenium.firefox.FirefoxOptions;import org.openqa.selenium.firefox.FirefoxProfile;import java.time.Duration;public class TestStuff { private static final String FIREFOX_DRIVER_PATH = System.getProperty("user.dir") +"\\geckodriver.exe"; public static void main(String[] args){ System.setProperty("webdriver.gecko.driver", FIREFOX_DRIVER_PATH); FirefoxProfile firefoxProfile = new FirefoxProfile(); firefoxProfile.setPreference("browser.download.folderList", 2); firefoxProfile.setPreference("browser.download.manager.showWhenStarting", false); firefoxProfile.setPreference("browser.download.alwaysOpenPanel", false); firefoxProfile.setPreference("browser.download.dir", System.getProperty("user.dir") ); firefoxProfile.setPreference("browser.helperApps.neverAsk.saveToDisk", "application/pdf"); firefoxProfile.setPreference("pdfjs.disabled", true); firefoxProfile.setPreference("plugin.scan.Acrobat", "99.0"); firefoxProfile.setPreference("plugin.scan.plid.all", false); FirefoxOptions options = new FirefoxOptions(); options.addPreference("general.useragent.override", "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:142.0) Gecko/20100101 Firefox/142.0"); options.setProfile(firefoxProfile); WebDriver driver = new FirefoxDriver(options); driver.manage().timeouts().pageLoadTimeout(Duration.ofSeconds(2)); try { driver.get("https://freetestdata.com/wp-content/uploads/2021/09/Free_Test_Data_100KB_PDF.pdf"); } catch(TimeoutException e) { System.out.println("Timeout occurred"); } driver.close(); System.out.println("Test done"); }}





