So after my code runs a new window shows up to download a CSV. A window pops up to either save the file or to open it with excel. How would I change windows to download that csv to a path using selenium.
public class automation {
public static void main(String[] args) {
FirefoxProfile profile = new FirefoxProfile();
String path = "C:\\Users\\K344975\\Desktop";
profile.setPreference("browser.download.dir",path);
profile.setPreference("browser.download.manager.showWhenStarting",false);
profile.setPreference("browser.helperApps.neverAsk.saveToDisk","application/xls;text/csv");
profile.setPreference("plugin.disable_full_page_plugin_for_types",
"application/octet-stream;application/csv;text/csv;application/vnd.ms-excel;application/xls;");
WebDriver driver = new FirefoxDriver(profile);
driver.get("");
String winHandle = driver.getWindowHandle();
System.out.println(winHandle);
//driver.quit();
}
}
I also tried making a profile
Well you have firstly patch profile and only after it create browser, and for plugin disable you could use
profile.setPreference("plugin.disable_full_page_plugin_for_types",
"application/octet-stream;application/csv;text/csv;application/vnd.ms-excel;")
Related
While automating via Selenium WebDriver, I have the below scenario. On a window, I copy the link and want to open the link on the new window(not in the new tab) and want to set focus on the new window. (Here the second window is not the child window of the first window)please help
You can do something like this
WebDriver driverOne=new ChromeDriver();
// navigate to your desired URL
driverOne.get("http://www.yourwebsite.com/");
// Do your stuff and copy the new link
// string newURL;
WebDriver driverSecond=new ChromeDriver();
driverSecond.get(newURL);
driverSecond will have a focus on the new window and once your actions are complete close the driverSecond.
In Selenium 4 (currently in beta), you the following will open a new window then automatically switch to the window:
#Test
public void openNewWindowForTestProjectBlog () {
WebDriver newWindow = driver.switchTo().newWindow(WindowType.WINDOW);
newWindow.get("https://blog.testproject.io/");
System.out.println(driver.getTitle());
}
//assume - multiple windows are opened by clicking link or a button.
Set<String> windows = driver.getWindowHandles();
for (String window : windows)
{
if (driver.getTitle().contains("***Something that is on new window***"))
{
driver.switchTo().window(window);
//To get title of new window
System.out.println(driver.switchTo().window(window).getTitle());
}
}
I have written the following code to disable the Chrome PDF viewer so that the PDF file can be downloaded automatically in the C:\downloads folder when the link is opened in Chrome.
ChromeOptions options = new ChromeOptions();
Map<String, Object> prefs = new HashMap<>();
prefs.put("download.default_directory", "C:\\downloads");
prefs.put("download.prompt_for_download", false);
prefs.put("plugins.always_open_pdf_externally", true);
options.setExperimentalOption("prefs", prefs);
options.addArguments("--test-type");
options.addArguments("--disable-extensions");
driver = new ChromeDriver(options);
Unfortunately the PDF viewer does not get disabled properly I believe. Here's what I get with this code when I open that PDF url:
Even if I enable the Download PDF files instead of automatically opening them in Chrome, I still get the above result.
Is there any other solution to get the file downloaded automatically in Chrome?
I managed automatic PDF download in Chrome with loading existing browser profile. Maybe you need just a profile without PDF viewer.
public class WebdriverSetup {
public static String chromedriverPath = "C:\\Users\\pburgr\\Desktop\\selenium-tests\\GCH_driver\\chromedriver.exe";
public static String chromeProfilePath = "C:\\Users\\pburgr\\AppData\\Local\\Google\\Chrome\\User Data";
public static WebDriver driver;
public static WebDriver startChromeWithCustomProfile() {
System.setProperty("webdriver.chrome.driver", chromedriverPath);
ChromeOptions options = new ChromeOptions();
options.addArguments("user-data-dir=" + chromeProfilePath);
driver = new ChromeDriver(options);
driver.manage().window().maximize();
return driver;
}
public static void shutdownChrome() {
driver.close();
driver.quit();
}
}
I use selenium WebDriver. I am trying to run following scenario.
I launch a url, and I want to add a condition that if there is any url opened other than the one I intended, I want to close it.
Following is my code, I will explain whats happening with it below.
if (config.getProperty("browser").equals("Chrome"))
{
System.setProperty("webdriver.chrome.driver", "chromedriver.exe");
ChromeOptions options = new ChromeOptions();
options.addArguments("disable-infobars");
options.addArguments("--start-maximized");
driver = new ChromeDriver(options);
selectServer();
String currentURL = driver.getCurrentUrl();
if (currentURL != config.getProperty("production") || currentURL != config.getProperty("staging") || currentURL != config.getProperty("development"))
{
Thread.Sleep(10000); //for Debugging purpose
driver.close();
}
}
I have a config.properties file where I set the browser / server selection.
Now what happens is, when I launch the test, chrome launches and:
Chrome settings window opens and it asks me to restore default settings. (Window in display)
My intended URL opens up. (hidden)
When I run the test, the test passes but Chrome Settings window does not close. I tried to print the current URL , and it returns the production server URL which is my intended URL but the browser window in display is not my production URL.
Based on your response in comments, I believe you need to switch to the settings tab, close that tab, then switch back to the original tab. The below code should do that:
public static void closeBrowserTab() {
String originalHandle = driver.getWindowHandle();
for (String handle : driver.getWindowHandles()) {
if (!handle.equals(originalHandle)) {
driver.switchTo().window(handle);
driver.close();
break;
}
}
driver.switchTo().window(originalHandle);
}
I am working on frame based website. I am using selenium 2.47.1 & PhantomJS 1.9.2. I have written Automation Script & run it using firefox driver, it works perfectly. I am trying to execute the code with help PhanthomJS driver. But whenever I am trying to execute the it gives NoSuchFrameFoundException. My script is given below...
public class iFrame {
public String baseUrl = "https://test5.icoreemr.com/interface/login/login.php";
public WebDriver cd;
String scenarioName = "Sheet1";
ExcelLibrary ex = new ExcelLibrary();
#BeforeTest
public void SetBaseUrl() {
Capabilities caps = new DesiredCapabilities();
((DesiredCapabilities) caps).setJavascriptEnabled(true);
((DesiredCapabilities) caps).setCapability(
PhantomJSDriverService.PHANTOMJS_EXECUTABLE_PATH_PROPERTY,
"C:\\Users\\Probe7\\Downloads\\phantomjs-1.9.2-windows\\phantomjs.exe"
);
this.cd = new PhantomJSDriver(caps);
cd.get(baseUrl);
cd.manage().window().maximize();
}
#Test(priority = 0)
/* Login into the Application */
public void Login() {
cd.manage().timeouts().implicitlyWait(25, TimeUnit.SECONDS);
cd.switchTo().frame("Login");
System.out.println("Control Moved to Login Frame");
String UserName = ex.getExcelValue(scenarioName, 2, 4);
cd.findElement(By.xpath("//body/center/form/table/tbody/tr/td/div/div[2]/table/tbody/tr[1]/td[2]/input")).sendKeys(UserName);
}
Above code gives following exception..
org.openqa.selenium.NoSuchFrameException: No frame element found by name or id Login
Eventhough same script works perfectly in firefox driver, but not in PhantomJS.
Please advice me what went wrong?? I am looking into this nearly a day, but didn't find any solution.. Please help me on this?
Thanks in Advance...
I just write a test which is supposed to download pdf files via webApp(Yep, I know, I should not do it on selenium, but You know, Orders.)
What do I need?
For diffrent scenarios I have to download difrent pdf, rename it and place to custom catalog. So, I have to handle with system modal window.
Everything works great, so test is run on remote host, and when I click to download the file I handle the system modal window(I used robotil package, it is extended robot class which allow us use robot class on remote host) so I use robotil class to type path to file, and file name on system modal and then click "Enter" to confirm and save the file. This is everything I need and it works, so where is the problem? here: SOMEONE should be logged to remote host, if Im logged via rdp and looks at screen(and doing my stuff on my host) then everything is great, but for the case when no one is logged, it looks like that during tests webbrowswer do not have a FOCUS, so everytime robotil class do some action this action is not focused on webbroswer(as it should).
test class:
#Test
public void compareDeposits() throws Exception {
HomePage homePage = new HomePage(driver);
PageFactory.initElements(driver, homePage);
PrintDepositsPage printDepositsPage = (PrintDepositsPage) homePage.openViaUrl(Data.baseUrl).openViewViaTopMenu(
ETopMenuItem.PrintDeposits);
((PrintDepositsPage) printDepositsPage).goToPrintedDepositsTab();
printDepositsPage.getPrintedDepositsDateRangeFromInput().click();
printDepositsPage.getPrintedDepositsDateRangeFromInput().clear();
printDepositsPage.getPrintedDepositsGoButton().click();
printDepositsPage.getFirstRecordOnPrintedDepositsTab().click();
handler.getRobot().mouseClick(371, 274, InputEvent.BUTTON1_MASK);// get focus
printDepositsPage.getPrintButtonEnabled().click();
handler.downloadFile("DepositTest");
handler object declaration:
class SystemModalWindowHandler {
private RemoteWebDriver driver;
private Date date = new Date();
private DateFormat dateFormat = new SimpleDateFormat("yyy/mm/dd");
private String extendedTestName = dateFormat.format(date).replace("/", ".") + ".pdf";
private Robotil robotil = new Robotil("xxxxx", 6667);
public Robotil getRobot(){
return robotil;
}
public void downloadFile(String testFileName) throws AWTException, InterruptedException {
boolean continueBool = true;
while (continueBool) {
String pathToTestFile = new String("C:\\DiffPdfData\\" + testFileName + "\\"
+ extendedTestName);
Thread.sleep(3000);
for (int i = 0; i < pathToTestFile.length(); i++) {
System.out.println(KeyStroke.getKeyStroke(pathToTestFile.charAt(i)) + " = "
+ (int) pathToTestFile.charAt(i));
if ((int) pathToTestFile.charAt(i) == 58) {
robotil.pressKey(KeyEvent.VK_SHIFT);
robotil.pressAndReleaseKey(KeyEvent.VK_SEMICOLON);
robotil.releaseKey(KeyEvent.VK_SHIFT);
}
else {
robotil.pressAndReleaseKey(KeyEvent.getExtendedKeyCodeForChar((int) pathToTestFile.charAt(i)));
}
}
robotil.pressAndReleaseKey(KeyEvent.VK_ENTER);
continueBool = false;
}
is there any way to get focus on webbrowser when no one is logged in?.
I believe that using the mentioned strategy you won't be able to accomplish it without logged-in user. So I suggest you to use a simpler solution.
You can configure Firefox the directly download the files - File types and download actions
If you don't want to hardcode the setting for your browser, you can setup a specific FF profile only for your tests, where you can configure where you want the files to be downloaded.
FirefoxProfile firefoxProfile = new FirefoxProfile();
firefoxProfile.setPreference("browser.download.folderList",2);
firefoxProfile.setPreference("browser.download.manager.showWhenStarting",false);
firefoxProfile.setPreference("browser.download.dir","c:\\downloads");
firefoxProfile.setPreference("browser.helperApps.neverAsk.saveToDisk","text/csv");
WebDriver driver = new FirefoxDriver(firefoxProfile);
Chrome Driver:
String downloadFilepath = "/path/to/download";
HashMap<String, Object> chromePrefs = new HashMap<String, Object>();
chromePrefs.put("profile.default_content_settings.popups", 0);
chromePrefs.put("download.default_directory", downloadFilepath);
ChromeOptions options = new ChromeOptions();
options.setExperimentalOption("prefs", chromePrefs);
DesiredCapabilities cap = DesiredCapabilities.chrome();
cap.setCapability(CapabilityType.ACCEPT_SSL_CERTS, true);
cap.setCapability(ChromeOptions.CAPABILITY, options);
WebDriver driver = new ChromeDriver(cap);