I am trying to download a .pdf to my local so that I can use Apache PDFBox to read the text from it and verify it as a part of my test suite. I have already found some code to download the pdf from Firefox by hitting a URL. This does not work for me since the pdf I am working with is a confidential document so it is not exposed by a URL, instead loaded within PDF Viewer as a popup window. Does anyone know how to hit the download button within the Firefox PDF Viewer after I have loaded the PDF Viewer in the browser?
I have tried looking it up by the element's id which = "download":
(new WebDriverWait(driver, 10)).until(ExpectedConditions.presenceOfElementLocated(By.id("download")));
driver.findElement(By.id("download")).click();
Unfortunately this does not work as it says it cannot find the element. Anyone know a workaround?
UPDATE: The pop-up window I described was an iframe element. This caused the inability to find the "download" element. Fixed with #4M01's switchTo() answer.
As you mentioned,
instead loaded within PDF Viewer as a popup window
You need to handle switching between different windows using switchTo() method of the driver object.
Below code working fine for me without an issue and I'm able to click on download icon.
public class FirefoxPDFTest {
WebDriver driver;
#BeforeClass
void Setup(){
System.setProperty("webdriver.gecko.driver", "C:\\Automation\\Selenium\\drivers\\geckodriver.exe");
driver = new FirefoxDriver();
driver.manage().window().maximize();
}
#Test
void downloadPDF(){
driver.get("http://www.pdf995.com/samples/pdf.pdf");
waitTillPageLoad();
driver.findElement(By.id("download")).click();
}
private void waitTillPageLoad(){
new WebDriverWait(driver, 30).until(driver -> ((JavascriptExecutor) driver).executeScript("return document.readyState").equals("complete"));
}
#AfterClass
void tearDown(){
driver.close();
driver.quit();
}
}
just use following code for clicking download button:
driver.findElement(By.xpath("//button[#id='download']")).click();
Thread.sleep(8000);
Robot robot = new Robot();
robot.keyPress(KeyEvent.VK_ENTER);
robot.keyRelease(KeyEvent.VK_ENTER);
We can handle the download popup in Firefox browser using Firefox browser settings and Firefox Profile setting using WebDriver.
Step 1: Update the setting in Firefox browser.
Open Firefox browser and navigate to Tools -> Options
Navigate to Applications.
Set the Action type as ‘Save File’ for PDF.
Step 2: Initialize FireFoxDriver using FirefoxProfile
File downloadsDir = new File("");
// Set Preferences for FirefoxProfile.
FirefoxProfile profile = new FirefoxProfile();
profile.setPreference("browser.download.folderList", 2);
profile.setPreference("browser.download.dir", downloadsDir.getAbsolutePath());
profile.setPreference("browser.download.manager.alertOnEXEOpen", false);
profile.setPreference("browser.helperApps.neverAsk.saveToDisk",
"application/msword, application/csv, application/ris, text/csv, image/png, application/pdf, text/html, text/plain, application/zip, application/x-zip, application/x-zip-compressed, application/download, application/octet-stream");
profile.setPreference("browser.download.manager.showWhenStarting", false);
profile.setPreference("browser.download.manager.focusWhenStarting", false);
profile.setPreference("browser.download.useDownloadDir", true);
profile.setPreference("browser.helperApps.alwaysAsk.force", false);
profile.setPreference("browser.download.manager.alertOnEXEOpen", false);
profile.setPreference("browser.download.manager.closeWhenDone", true);
profile.setPreference("browser.download.manager.showAlertOnComplete", false);
profile.setPreference("browser.download.manager.useWindow", false);
profile.setPreference("services.sync.prefs.sync.browser.download.manager.showWhenStarting", false);
profile.setPreference("pdfjs.disabled", true);
// Initialize the FireFoxDriver instance.
FirefoxDriver webDriver = new FirefoxDriver(profile);
Step 3: Execute the Script
Execute the script which clicks on the download PDF icon.
Result: PDF file will be downloaded and the Download popup will not be displayed.
You can handle the download icon (using Firefox), by using the following (C#) code:
IWebElement element = Driver.FindElement(By.Id("download"));
IJavaScriptExecutor executor = (IJavaScriptExecutor)Driver;
executor.ExecuteScript("arguments[0].click();", element);
Related
I'm practicing and trying to parse behance.net to retrieve .jpg files.
First, I tried with JSOUP, but I only receives and JS code without any useful code. Then i tried with selenium:
System.setProperty("webdriver.chrome.driver", "S:\\behance-id\\src\\main\\resources\\chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.get("https://www.behance.net/gallery/148589707/Hercules-and-Randy");
String str = driver.getPageSource();
And I got same result. Through Google Chrome inspect option I found what I need:
But I cannot acces to this source page via Selenium and JSOUP and other instruments.
I only receive this with <script> tags:
Is it possible?
That page is loading its resources dynamically, after the original HTML, so you should use waits in Selenium. This is the Java example for waiting an element to be loaded in page, from the documentation:
WebDriver driver = new ChromeDriver();
driver.get("https://google.com/ncr");
driver.findElement(By.name("q")).sendKeys("cheese" + Keys.ENTER);
// Initialize and wait till element(link) became clickable - timeout in 10 seconds
WebElement firstResult = new WebDriverWait(driver, Duration.ofSeconds(10))
.until(ExpectedConditions.elementToBeClickable(By.xpath("//a/h3")));
// Print the first result
System.out.println(firstResult.getText());
The documentation can be found at https://www.selenium.dev/documentation/webdriver/waits/
I would like to automate the authentication process in https://appleid.apple.com/ using java webdriver selenium, but html elements of the form doesn't loaded in the DOM
to my knowledge, Selenium webdriver interpret the markup as a browser does.
And It apply the CSS styles, run the JavaScript and the dynamically
rendered content be added to the DOM
Why HTML elements are not loaded in the DOM ?
How can I proceed, to fix it and load all elements in the DOM, exactly like a browser ?
N.B : https://appleid.apple.com/ website use Mustache.JS (logic-less template)
public static void main(String[] args) {
System.setProperty("webdriver.chrome.driver", "chromedriver.exe");
ChromeOptions options = new ChromeOptions();
options.addArguments("--headless", "--disable-gpu", "--window-size=1920,1200", "--ignore-certificate-errors");
WebDriver driver = new ChromeDriver(options);
driver.get("https://appleid.apple.com/");
waitForPageLoadComplete(driver, 30);
//can't found input name element
WebElement inputName = driver.findElement(By.id("account_name_text_field"));
System.out.println(driver.getPageSource());
}
The element you are trying to find is inside an iFrame. You will need to switch to this iFrame first and then proceed with finding the element as you already have.
driver.switchTo().frame("aid-auth-widget-iFrame");
WebElement inputName = driver.findElement(By.id("account_name_text_field"));
You can find some additional information about switching to iFrames here: https://www.guru99.com/handling-iframes-selenium.html
I want to scroll down my web page. What Java command should I use in Selenium?
Scrolling down a web page is not a valid usecase which can be validated perhaps you want to scroll down to bring a WebElement within the Viewport to interact with it. To achieve that you can use the executeScript() method as follows :
((JavascriptExecutor)driver).executeScript("arguments[0].scrollIntoView();", element);
Use the below code and try,
JavascriptExecutor js = (JavascriptExecutor) driver;
// Launch the application
driver.get("http://demo.guru99.com/test/guru99home/");
//This will scroll the web page till end.
js.executeScript("window.scrollTo(0, document.body.scrollHeight)");
Please refer the code below :
1) Using Action class****
WebDriver driver = new ChromeDriver();
//Creating an object 'action'
Actions action = new Actions(driver);
//open SoftwareTestingMaterial.com
driver.get(Site URL); // Give site URL as name of the web page
//sleep for 3secs to load the page
Thread.sleep(3000);
//SCROLL DOWN
action.sendKeys(Keys.PAGE_DOWN).build().perform();
Thread.sleep(3000);
//SCROLL UP
action.sendKeys(Keys.PAGE_UP).build().perform();
Before tagging this as duplicate. Please read the Question. i have seen many answers for this kind of question. But none of them really worked.
System.setProperty("webdriver.gecko.driver", "src/test/driver/geckodriver.exe");
WebDriver driver = new FirefoxDriver();
driver.get("http://google.com");
driver.findElement(By.cssSelector("body")).sendKeys(Keys.CONTROL +"t");
driver.get("https://www.facebook.com");
this my code. When I run this instead of opening a new tab its just opening in Current tab.How can i open second link in new tab?
You can use javascript for this in ur selenium code :-
JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("window.open('https://www.google.com','_blank');");
Can someone guide me how I can achieve the following:
I am using selenium web driver java.
Whenever I click the preview button on the webpage, the pdf is opened in a new browser and I need to save that pdf with the name given dynamically.
So far I am able to click the preview button and a new browser is opened with the pdf. Here the browser doesn't have url.
After the pdf is open I am sending keys control+s.
Then save dialog window appears. I am stuck here about how to save pdf to the local drive.
The main browser is IE but i am trying in Firefox first
You can try this code :-I think this is what you are looking for. let me know If this what you are expecting.
System.setProperty("webdriver.gecko.driver", "D:/geckodriver.exe");
WebDriver driver = new FirefoxDriver();
driver.manage().window().maximize();
driver.get("http://www.adobe.com/content/dam/Adobe/en/devnet/acrobat/pdfs/pdf_open_parameters.pdf");
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
Thread.sleep(2000);
java.awt.Robot robot = new java.awt.Robot();
Thread.sleep(1000);
robot.keyPress(KeyEvent.VK_CONTROL);
robot.keyPress(KeyEvent.VK_S);
robot.keyRelease(KeyEvent.VK_S);
robot.keyRelease(KeyEvent.VK_CONTROL);
Thread.sleep(2000);
robot.keyPress(KeyEvent.VK_ENTER);
Thread.sleep(2000);
robot.keyPress(KeyEvent.VK_TAB); // file replace move to yes button
Thread.sleep(2000);
robot.keyPress(KeyEvent.VK_ENTER); // hit enter
Just first execute the code, see if it is working, and is it what you want.
Last three lines of code are written for replace existing pdf file. So you just first comment those three lines, execute the code and from next time, include last three lines of code
You need to use Robot Class to handle events.
And let me know whether this is working at your end.
I think you should try to download the file immediately instead of trying to manage that browse window.
You can set the attribute download of the a element, and then click on the element. See code below:
WebElement pdf = driver.findElement(By.cssSelector("a"));
String script = "arguments[0].setAttribute('download');"
((JavascriptExecutor)driver).executeScript(script, pdf);
pdf.click();