Triggering events in chrome from java - java

Is it possible to interact with Chrome from within a java application? Say for example fill in an input field and submit/trigger a button event?

Yes. See WebDriver's ChromeDriver.
Example usage taken from docs:
// Optional, if not specified, WebDriver will search your path for chromedriver.
System.setProperty("webdriver.chrome.driver", "/path/to/chromedriver");
WebDriver driver = new ChromeDriver();
driver.get("http://www.google.com/xhtml");
Thread.sleep(5000); // Let the user actually see something!
WebElement searchBox = driver.findElement(By.name("q"));
searchBox.sendKeys("ChromeDriver");
searchBox.submit();
Thread.sleep(5000); // Let the user actually see something!
driver.quit();

Related

Unable to locate the elements of SmartGWT application using Selenium in IE browser

I'm testing a GWT + SMARTGWT application like Paint and I'm trying to locate the elements of this web application using Selenium Webdriver. The method which I have used to locate the elements is by the relative XPath of those elements but the problem which I am currently facing is that this method is working correctly on the browsers like Chrome, Firefox, and Edge but not on the IE browser. The version of IE on my PC is 11.1593.14393.0. In the IE browser, this relative XPath method is giving a TimeOutException. I have given the explicit wait:
wait.until(ExpectedConditions.elementToBeClickable(webelement));
The IE browser is not able to find the element. I am also getting the following exception sometimes for other elements:
Exception in thread "main" org.openqa.selenium.InvalidSelectorException: Unable to locate an element with the xpath expression //img[contains(#src,'Insert XXX'] because of the following error:
Error: Bad token: ]
Among the troubleshooting solutions to this issue, I tried enabling/disabling the protected mode in IE for all the levels but this method didn't work. Along with that, I also tried checking the box next to the option - "Allow active content to run files on My Computer" but this method also failed to work.
What should I do to fix my issue?
This is my code. Here firstly, I will click on the Insert button located on the top bar of the application and after clicking on the Insert button, a window will launch on which I will click on the Close button.
public static void main(String[] args) throws InterruptedException {
System.setProperty("webdriver.ie.driver", "D:\\SELENIUM\\Drivers\\iedriverserver.exe");
WebDriver driver = new InternetExplorerDriver();
Thread.sleep(3000);
driver.get(baseURL);
WebDriverWait wait = new WebDriverWait(driver, 10);
final String InsertPath = "//img[contains(#src,'Insert XXXX')]";
final String closePath="//img[contains(#src,'close')]";
WebElement Insert = driver.findElement(By.xpath(InsertPath));
wait.until(ExpectedConditions.elementToBeClickable(Insert));
Thread.sleep(2000);
Insert.click();
WebElement close = driver.findElement(By.xpath(closePath));
wait.until(ExpectedConditions.elementToBeClickable(close));
Thread.sleep(3000);
close.click();
}
}
Edit: I also used finding the element using Javascript executor in my code as follows:
WebElement Insert = driver.findElement(By.xpath(InsertPath));
Thread.sleep(2000);
JavascriptExecutor jse = (JavascriptExecutor) driver;
jse.executeScript("arguments[0].click();", Insert);
Sadly, this method also failed to work in the IE browser.
So, I was able to locate the elements by using the latest driver of the Internet Explorer and giving the following desired capabilities in my code to the IE browser.
DesiredCapabilities ieCapabilities = DesiredCapabilities.internetExplorer();
ieCapabilities.setCapability("requireWindowFocus", true);
ieCapabilities.setCapability("unexpectedAlertBehaviour", "accept");
ieCapabilities.setCapability("ignoreProtectedModeSettings", true);
ieCapabilities.setCapability("disable-popup-blocking", true);
ieCapabilities.setCapability("enablePersistentHover", true);*/
System.setProperty("webdriver.ie.driver", "D:\\IEDriverServer.exe");
WebDriver driver = new InternetExplorerDriver(ieCapabilities);

Not able to save page in selenium webdriver

At the end, I am not able to click on save button. The last click is not working for me.
System.setProperty("webdriver.chrome.driver" , "C:\\Users\\gausia.fatima\\Downloads\\automation\\chromedriver_win32\\chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
driver.get("http://www.idfystaging.com/users/sign_in");
driver.findElement(By.name("user[login]")).sendKeys("themanager#mailinator.com");
driver.findElement(By.name("user[password]")).sendKeys("Password123");
driver.findElement(By.name("commit")).click();
driver.get("http://www.idfystaging.com/profiles/new?company_id=189");
Select mydrpdwn = new Select(driver.findElement(By.id("company_id")));
mydrpdwn.selectByVisibleText("Fringe A Division");
driver.findElement(By.id("email_addresses")).sendKeys("awesome1#mailinator.com");
driver.findElement(By.id("counts_aadhaar")).sendKeys("1");
//WebDriverWait wait = new WebDriverWait(driver,30);
//wait.until(ExpectedConditions.presenceOfElementLocated(By.name("commit")));
driver.findElement(By.name("commit")).submit();
System.out.println("candiate is invited.");
//driver.close();
In the "Invite Candidates" page, you have to submit button with the same name as "commit", so selenium is throwing error.
http://www.idfystaging.com/profiles/new?company_id=189
Use the CssSelectorto get the control and submit them.
Java code un tested but it should work.
driver.findElement(By.cssSelector("input.f21")).Submit();
Note : This is c# code and I tested
driver.FindElement(By.CssSelector("input.f21")).Submit();
as name=commit returns two elements in the page, should use more strict selector to find the Invite button.
Try the following code to click on Invite button:
driver.findElement(By.xpath("//input[#value='Invite']")).click();
or
driver.findElement(By.xpath("//input[#value='Invite']")).submit();
You can use following code. I have modified it and it is working fine. Please check if it is working fo you.
System.setProperty("webdriver.chrome.driver" , "C:\\Users\\gausia.fatima\\Downloads\\automation\\chromedriver_win32\\chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
driver.get("http://www.idfystaging.com/users/sign_in");
driver.findElement(By.id("focus_on_load")).sendKeys("themanager#mailinator.com");
driver.findElement(By.id("user_password")).sendKeys("Password123");
driver.findElement(By.name("commit")).click();
Thread.sleep(5000);
driver.navigate().to("http://www.idfystaging.com/profiles/new?company_id=189");
Select mydrpdwn = new Select(driver.findElement(By.id("company_id")));
mydrpdwn.selectByVisibleText("Fringe A Division");
driver.findElement(By.id("email_addresses")).sendKeys("awesome1#mailinator.com");
driver.findElement(By.id("counts_aadhaar")).sendKeys("1");
driver.findElement(By.cssSelector("input.f21")).click();
System.out.println("candiate is invited.");

How can I tell Selenium to press cancel on a print popup?

I am checking whether or not a page appears using Selenium. When I click the page, however, a printer print prompt appears (like the window that says select printer and such). How can I have Selenium close this window by hitting cancel?
I tried looking to alerts, but it seems like those will not work since the print window is a system prompt. It does not recognize any alerts appearing.
The most recent I tried using is by just sending keys like tab and enter in order to have the cancel button selected, however, it doesn't recognize any keys as being pressed.
How can I handle this case?
public static boolean printButton() throws Exception {
WebDriver driver = new FirefoxDriver();
driver.get("website");
try {
Thread.sleep(3000);
WebElement temp = driver.findElement(By.xpath("//*[#id='block-print-ui-print-links']/div/span/a"));
temp.click();
Actions action = new Actions(driver);
action.sendKeys(Keys.TAB).sendKeys(Keys.ENTER);
Thread.sleep(6000);
}
catch (Exception e) {
System.out.println("No button.");
driver.close();
return false;
}
I would simply disable the print dialog by overriding the print method :
((JavascriptExecutor)driver).executeScript("window.print=function(){};");
But if you goal is to test that the printing is called then :
// get the print button
WebElement print_button = driver.findElement(By.cssSelector("..."));
// click on the print button and wait for print to be called
driver.manage().timeouts().setScriptTimeout(20, TimeUnit.SECONDS);
((JavascriptExecutor)driver).executeAsyncScript(
"var callback = arguments[1];" +
"window.print = function(){callback();};" +
"arguments[0].click();"
, print_button);
If you are going for testing only Chrome browser here is mine solution. Because of 'Robot' class or disabling print didn't work for my case.
// Choosing the second window which is the print dialog.
// Switching to opened window of print dialog.
driver.switchTo().window(driver.getWindowHandles().toArray()[1].toString());
// Runs javascript code for cancelling print operation.
// This code only executes for Chrome browsers.
JavascriptExecutor executor = (JavascriptExecutor) driver.getWebDriver();
executor.executeScript("document.getElementsByClassName('cancel')[0].click();");
// Switches to main window after print dialog operation.
driver.switchTo().window(driver.getWindowHandles().toArray()[0].toString());
Edit: In Chrome 71 this doesn't seem to work anymore since the script can't find the Cancel button. I could make it work by changing the line to:
executor.executeScript("document.querySelector(\"print-preview-app\").shadowRoot.querySelector(\"print-preview-header\").shadowRoot.querySelector(\"paper-button.cancel-button\").click();");
Actually you can't handle windows (OS) dialogs inside Selenium WebDriver.
This what the selenium team answers here
The current team position is that the print dialog is out of scope for
the project. WebDriver/Selenium is focused on emulating a user's
interaction with the rendered content of a web page. Other aspects of
the browser including, but not limited to print dialogs, save dialogs,
and browser chrome, are all out of scope.
You can try different approach like AutoIt
we can also use key for handling the print or press the cancel button operation. and it works for me.
driver.switchTo().window(driver.getWindowHandles().toArray()[1].toString());
WebElement webElement = driver.findElement(By.tagName("body"));
webElement.sendKeys(Keys.TAB);
webElement.sendKeys(Keys.ENTER);
driver.switchTo().window(driver.getWindowHandles().toArray()[0].toString());
Native window based dialog can be handled by AutoItX as described in the following code
File file = new File("lib", jacobDllVersionToUse);
System.setProperty(LibraryLoader.JACOB_DLL_PATH, file.getAbsolutePath());
WebDriver driver = new FirefoxDriver();
driver.get("http://www.joecolantonio.com/SeleniumTestPage.html");
WebElement printButton = driver.findElement(By.id("printButton"));
printButton.click();
AutoItX x = new AutoItX();
x.winActivate("Print");
x.winWaitActive("Print");
x.controlClick("Print", "", "1058");
x.ControlSetText("Print", "", "1153", "50");
Thread.sleep(3000); //This was added just so you could see that the values did change.
x.controlClick("Print", "", "2");
Reference : http://www.joecolantonio.com/2014/07/21/selenium-how-to-handle-windows-based-dialogs-and-pop-ups/
Sometimes 2 different statements as above (webElement.sendKeys(Keys.TAB)
webElement.sendKeys(Keys.ENTER)) will not work, you can use with combination of Tab and Enter keys as below, This will close the Print preview window.
Using C# :
Driver.SwitchTo().Window(Driver.WindowHandles[1]);
IWebElement element = Driver.FindElement(By.TagName("body"));
element.SendKeys(Keys.Tab + Keys.Enter);
Driver.SwitchTo().Window(Driver.WindowHandles[0]);
Erçin Akçay answer updated.
// Choosing the second window which is the print dialog.
// Switching to opened window of print dialog.
driver.switchTo().window(driver.getWindowHandles().toArray()[1].toString());
// Runs javascript code for cancelling print operation.
// This code only executes for Chrome browsers.
JavascriptExecutor js = (JavascriptExecutor)driver;
js.executeScript("document.querySelector(\"body > print-preview-app\").shadowRoot.querySelector(\"#sidebar\").shadowRoot.querySelector(\"print-preview-button-strip\").shadowRoot.querySelector(\"div > cr-button.cancel-button\").click();");
// Switches to main window after print dialog operation.
driver.switchTo().window(driver.getWindowHandles().toArray()[0].toString());

Selenium WebDriver Automation for Vaadin components

I am using Selenium Java WebDriver to automate a Vaadin based web application. When I navigate to a page and click a button it opens up another small window which does not look like a popup to me. It seems the subwindow is dynamically added to the main html.
Does anyone have any idea on how to identify Vaadin elements in Selenium?
try with
driver.findElement(By.className("v-window")) for the entire window or
driver.findElement(By.className("v-window-contents")) for the window content.
When you creating test be sure to run this test after the browser is open. Sometimes test starts, but browser is not open. I put Thread.sleep(1000); in #Before class, to be sure chrome is open.
#Before
public void openBrowser() throws InterruptedException {
System.setProperty("webdriver.chrome.driver", "chromedriver");
driver = new ChromeDriver();
driver.get("http://localhost:8000");
Thread.sleep(1000);
}
and then
#Test
public void testLoginFormExists() {
WebElement login = driver.findElement(By.id("username"));
WebElement password = driver.findElement(By.id("password"));
...
}
or even better, check this answer: https://stackoverflow.com/a/9430377/1168786

Selenium web driver | java | unable to switch between firefox browser windows

Using Selenium Webdriver 2. java.
I would like to switch back in forth between two firefox browser windows. When I do I get: org.openqa.selenium.NoSuchWindoException: Unable to loacate window"{accb1cc2-74c9-3b4e-8f71-c0b184a037c4}"; duration or timeout:
Here is the java:
driver = new FirefoxDriver();
driver.get("http://mail.google.com");
String firstWindowHandle = driver.getWindowHandle();
System.out.println("handle of first window ="+firstWindowHandle);
Thread.sleep(1000);
driver = new FirefoxDriver();
driver.get("http://www.google.com");
// Get names of currently open windows
String secondWindowHandle = driver.getWindowHandle();
System.out.println("handle of first window ="+secondWindowHandle);
Thread.sleep(1000);
// It fails right here!
driver.switchTo().window(firstWindowHandle );
driver.get("http://www.lifehacker.com");
It prints the following to the console:
- handle of first window = {accb1cc2-74c9-3b4e-8f71-c0b184a037c4}
- handle of the second window = {f5256619-a36e-a441-9979-937da0abacd1}
All help is appreciated.
Unfortunately, you cannot switch between windows the way you are currently trying to do it - WebDriver lost the first window as soon as you instantiated a new instance.
You could try opening the second window via javascript and then switching back and forth from it:
window.open('http://www.bing.com','Bing','modal=yes,alwaysRaised=yes')
This is a bit of a hack, and could have the following problems:
Popup blockers may prevent the action
The browser must have javascript enabled
Future browser versions may break the hack
Complaining and murmuring from peers (and perhaps rightly so) because even though it might work, it's still a hack ;)
Some final thoughts:
Is there any particular reason it has to be the same driver instance?
If not, just switch between two driver instances:
FirefoxDriver driver = new FirefoxDriver();
driver.get("http://mail.google.com");
FirefoxDriver driver2 = new FirefoxDriver();
driver2.get("http://www.google.com");
Swtiching between 2 active Windows:
FirefoxDriver wd=new FirefoxDriver();
wd.get("https://irctc.co.in/");
wd.manage().timeouts().implicitlyWait(5000,TimeUnit.SECONDS);
WebElement wb=wd.findElement(By.linkText("Cabs"));
wb.click(); //Now 2 Windows are open
wd.manage().timeouts().implicitlyWait(5000,TimeUnit.SECONDS); //Wait for the complete page to load
Set<String> sid=wd.getWindowHandles(); //getWindowHandles() method returns the ids of all active Windows and its return type will be a Collection Set.
Iterator<String> it=sid.iterator(); //Using iterator we can fetch the values from Set.
String parentId=it.next();
System.out.println(parentId);
String childId=it.next();
System.out.println(childId);
wd.switchTo().window(childId); //swtiching control to child Window
wd.close(); //control returns to the parent Window.

Categories

Resources