How to perform automation in edge browser open using desktop application? - selenium

I have a Web application to automate using selenium and Java.
Application supports IE Browser on windows10 and for windows11 we have created an .lnk file to open same application in Edge browser because IE is no longer. And we have some videos to be streamed in application for which media player to be installed and more.
Scenario :
I have to open ABC.lnk application from desktop
Once clicked on ABC.lnk application, our application will open in Edge browser.
for step 1 : using below code to open ABC.lnk application
public static void openWindowApplication() {
String command = "C:\\Users\\Kasper\\Desktop\\ABC.lnk";
try {
Runtime.getRuntime().exec("cmd /c " + command);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Step 2 :
Edge driver initialization Code :
System.setProperty("webdriver.edge.driver", FileReaderManager.getInstance().getConfigReader().getDriverPath() + "/msedgedriver.exe");
//Creating an object of EdgeDriver
driver = new EdgeDriver();
driver.manage().window().maximize();
//Deleting all the cookies
driver.manage().deleteAllCookies();
//Specifiying pageLoadTimeout and Implicit wait
driver.manage().timeouts().pageLoadTimeout(40, TimeUnit.SECONDS);
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
I have used above code to achieve above scenarios. But 2 edge browsers are getting open and nothing is happening because of above code snippet and Step 1 is required to open ABC.lnk and application opens in edge browser on click on it.
And I have to perform automation on open browser through ABC.lnk click.
How can I perform automation in same edge browser open in step 1.
Thanks in advance.

Related

Link Click using selenium webdriver is giving timeout error, link is working fine on browser otherwise

I'm trying to write a piece of code using Testng in selenium, the problem is when i try to click a link, the code becomes unresponsive and gives error- Timed out receiving message from renderer
Tried driver.get("https://infostore.saiglobal.com/") instead of driver.findElement(By.linkText("Infostore")).click(); still remains unresponsive - Doesnot get directed to the webpage - https://infostore.saiglobal.com/
#Test
public void testSai() throws Exception {
driver.get("https://www.saiglobal.com/"); //open homepage
driver.findElement(By.id("CybotCookiebotDialogBodyButtonAccept")).click(); //accept cookie
driver.findElement(By.cssSelector("#sai-header > div > div.main-nav > div.store-box > div")).click(); //click on Login to open list
sleep(2);
driver.findElement(By.linkText("Infostore")).click(); //click on infostore to be redirected to https://infostore.saiglobal.com/
System.out.println(driver.getCurrentUrl());
Yes I have checked this issue and there is an workaround for this issue if you wish to have this.Try following code.
Take the href attribute value from the link element.
Delete all cookies.
driver.navigate().to(URL);
public static void main(String[] args){
System.setProperty("webdriver.chrome.driver", System.getProperty("user.dir") + File.separator + "\\Executables\\Chromedriver.exe");
WebDriver driver = new ChromeDriver();
WebDriverWait wait = new WebDriverWait(driver, 5);
Actions actions = new Actions(driver);
driver.get("https://www.saiglobal.com/");
driver.findElement(By.id("CybotCookiebotDialogBodyButtonAccept")).click();
WebElement element=wait.until(ExpectedConditions.elementToBeClickable(By.xpath("//div[#class='desktop-login']")));
actions.moveToElement(element).build().perform();
WebElement element1=wait.until(ExpectedConditions.elementToBeClickable(By.xpath("//div[#class='desktop-login']/ul/li/a[contains(text(),'Infostore')]")));
String str1=element1.getAttribute("href");
driver.manage().deleteAllCookies();
driver.navigate().to(str1);
System.out.println(driver.getCurrentUrl());
}
This seems to be an error with Selenium that the developers have been dealing with for over a year. They never really give a concrete answer as to what causes it or how to fix it.
The first port of call would be to make sure that your browser and Selenium are compatible. Try opening a different URL that you know works, and if the error persists then there is likely an error with the compatibility of your selenium and web browser. If it works, then there is something wrong with your website.
For reference, I opened your website using Python Selenium, and had no issues loading or interacting with elements. So the error is local to the software you are using.
The issue can also be caused by sleeps(no idea why), so try removing any sleeps and see if this stops the issue.

ChromeDriver execution waiting at driver.get(url)

My configuration as below:
Chrome - 65
Chromedriver exe - 2.67
My application throws up a credentials popup when I hit driver.get(url). I have used sikuli to enter the credentials on the chrome browser's credential popup.
Recently, we had an chrome 65 upgrade. Post this update, the execution stays blocked at line driver.get(url) until the credentials are entered manually on the popup. But, the sikuli code to handle the popup is on line next to driver.get(url).
Any workaround available, so that the execution comes out of line driver.get(url) inspite of the there being a popup so that my sikuli code can handle that?
Found solution for this , can be handled through thread concept ,
Thread t = new Thread(new Runnable() {
public void run() {
System.out.println(Thread.currentThread().getName());
driver.get(Thread.currentThread().getName());
}
}, url);
t.start();
// Next line of code :AutoIT or Robot or Sikuli to handle security pop-up

Selenium IE driver not able to find the correct page source

I have a login page which redirects to a page from where I need to extract some data from an element using selenium.
I am running the code from local eclipse using the IE driver but facing an issue as the pagesource is that of the initial web driver page after some time the IE browser does navigate to the page with some delay , but the page source remains the same and get a exception as no such element found.
Have tried to add implicity waits but did not work.
Any work around where I can induce a delay ?
DesiredCapabilities caps = DesiredCapabilities.internetExplorer();
caps.setCapability(InternetExplorerDriver.INTRODUCE_FLAKINESS_BY_IGNORING_SECURITY_DOMAINS, true);
caps.setCapability(InternetExplorerDriver.IGNORE_ZOOM_SETTING, true);
caps.setCapability(CapabilityType.ACCEPT_SSL_CERTS, true);
File file = new File("D:/IEDriverServer.exe");
System.setProperty("webdriver.ie.driver", file.getAbsolutePath());
driver = new InternetExplorerDriver(caps);
driver.get(baseUrl);
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
driver.manage().window().setSize(new Dimension(600, 600));
Based on your comment (to your question) that "It does not navigate beyond the first page of the driver having title 'WebDriver'", I gather you are not able to go to login page, enter credentials and click on some button that will redirect to 2nd page.
In that case, please make you that you are using appropriate version of Internet Explorer driver. I am using 64-bit version of Internet Explorer driver as I am using 64-bit version of Internet Explorer browser and 64-bit OS on my PC. If you are using 32-bit version of Internet Explorer browser and 32-bit OS, you will need to use 32-bit version of Internet Explorer driver. How to find which version of Internet Explorer browser we are using: By checking path of it's executable file, whether it is in "Program Files" or in "Program Files (x86)" folder. How to see whether OS is 32 bit or 64 bit: Right-click on "Computer" and select "Properties".
I think following code would work:
#BeforeTest
public void setup() {
System.setProperty("webdriver.ie.driver", "C:/Dependancies/IEDriverServer.exe");
driver = new InternetExplorerDriver();
}
#Test
public void test() throws InterruptedException {
driver.get("URL_of_login_page"); // Make sure the URL begins with 'http' or 'https'.
// Enter login credentials, click on 'Submit' button so that it will redirect to 2nd page.
Thread.sleep(15000); // Assuing 15 seconds is sufficient time for the 2nd page to load.
System.out.println("The 2nd page is loaded now.");
System.out.println(driver.getTitle()); // It should print page-title of 2nd page.
String source;
source = driver.getPageSource();
System.out.println(source);
}

Selenium Force Close Firefox

ProfilesIni profile = new ProfilesIni();
FirefoxProfile ff = profile.getProfile("ScreenCapture");
WebDriver driver = new FirefoxDriver(ff);
driver.manage().timeouts().implicitlyWait(15, TimeUnit.SECONDS);
driver.get(url);
Thread.sleep(8000);
File srcFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
driver.quit();
Shouldn't driver.manage().timeouts().implicitlyWait(15, TimeUnit.SECONDS); force a close of the selenium generated Firefox browser after 15 seconds? The browser just sits and says its transferring data for an hour+. Basically just hangs saying its transferring...
I am capturing ajax heavy pages which is why Im asking everything to wait for 8 seconds after page loads. But that should have nothing to do with the driver forcing a close after 15 seconds.
Where am I going wrong?
Details: Centos x64 6.4 with Firefox 10.0.12 and latest Selenium as of 10 min ago.
Is there something I can do in Java to go around this?
Question: How can I force close the Selenium generated Firefox window after N seconds?
If you use Junit along with Java, then some thing like this :-
#After
public void tearDown() throws Exception {
driver.quit();
String verificationErrorString = verificationErrors.toString();
if (!"".equals(verificationErrorString)) {
fail(verificationErrorString);
}
}
Note :-
To get a full skeleton of how it should be written just download the selenium IDE for FF and export some test case to Java /jUnit.
My linux knowledge is limited, but you can kill a process by running the linux command pkill.
driver.quit();
Thread.sleep(15000); //use a poll loop instead to check process running every 1 sec
Runtime rt = Runtime.getRuntime();
rt.exec("pkill firefox");
I think that the java process will need to have enough permissions to kill a process, but haven't tried it.
To follow up on Ardesco's comment, an example would look as follows:
ProfilesIni profile = new ProfilesIni();
FirefoxProfile ff = profile.getProfile("ScreenCapture");
WebDriver driver = new FirefoxDriver(ff);
driver.manage().timeouts().pageLoadTimeout(15, TimeUnit.SECONDS);
try {
driver.get(url);
} catch (TimeoutException e) {
System.out.println("15 seconds were over, force continue!");
} finally {
File srcFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
driver.quit();
}
The try part will run the request but when the timeout time set with pageLoadTimeout has been exceeded an exception is thrown which we catch. The finally part will be run regardless if the requested page was loaded properly in less than 15 seconds or whether an exception was thrown.
Implicit waits will not force a close of a browser after 15 seconds.
Implicit waits are used when trying to find elements in the DOM, they are not used when trying to load a page. If you want Selenium to stop trying to load a page after 15 seconds you will need to set a pageLoadTimeout, it's used like this:
driver.manage().timeouts().pageLoadTimeout(15, TimeUnit.SECONDS);
The default page load timeout is 0 (which means wait indefinitely), hence the behaviour that you are seeing.
(There is obviously an assumption here that the driver binary you are using has implemented this method.)
The JavaDoc for timeouts in Selenium is available Here

Handling Browser Authentication using Selenium

Does anyone know about handling Browser Authentication using Selenium or any other tool during automation?
EDIT in 2015:
This answer is outdated. WebDriver nowadays supports authentication! See How to handle authentication popup with Selenium WebDriver using Java
Original answer:
This is not handled very well by Selenium.
You can try using http://username:password#example.com/yourpage
instead of just http://example.com/yourpage
However, as far as I know, Firefox will still pop up a browser dialog requesting a confirmation.
You can try Robot if you're using Java (or any similar tool like AutoIt).
You could use driver.manage().addCookie() if you're using WebDriver.
Or a custom FirefoxProfile that has already passed the authentication once.
I spent days on this - literally.
Trying to get past browser level authentication within my company network to hit an application.
The solution was to use the 'unsername:password#' component within the URL, BUT to add a forward slash at the end of the login URL.
So total login URL looks like this (note the '/' after yourpage):
http://username:password#example.com/yourpage/
Works with Watir, Capybara and Selenium Webdriver.
Everything I have read on the Web didn't help me. So before making a request, like this:
driver.get(url);
you have to run a new thread like this:
RunScript runScript = new RunScript();
runScript.start();
In this case you are free to input login and password on another thread of follwing class
public class RunScript extends Thread {
#Override
public void run() {
try {
File file = new File("D:\\jacob-1.18-x86.dll");
System.setProperty(LibraryLoader.JACOB_DLL_PATH, file.getAbsolutePath());
AutoItX autoIt = new AutoItX();
Thread.sleep(2000);
autoIt.winActivate("yourWindowName", "");
autoIt.winWaitActive("yourWindowName");
if (autoIt.winExists("yourWindowName")) {
autoIt.send("username{TAB}", false);
autoIt.send("password{Enter}", false);
}
}
} catch (InterruptedException ex) {
//
}
}
}
All the hacks via auto-it, sikuli, etc. just wasting your time when you'll run it in your CI solution, using several browser types / OS / Version / Resolutions etc.
The way to do it correctly is to identify the authentication actual method and perform a login using Rest protocol for instance.
I used it to get the JSESIONID cookie and insert it to the selenium driver.
hint on that: go to a non-exiting url of the domian first, then set the cookie, then go to the required url - you are logged-in.
use: rest client authentication to get the JSESSION ID
and With this information:
browser().navigate(foo.getUrl()+"non-exiting-url");
//the information got from the rest client login:
Cookie cookie = new Cookie(name, value, domain, path, expiry, isSecure, isHttpOnly);
try {
driver.manage().addCookie(cookie);
} catch (Exception e) {
System.out.println(e.toString());
}
browser().navigate(foo.getUrl());
you can use auto IT script to handle this problem
WinWaitActive("[CLASS:Chrome_WidgetWin_1]", "", time)
Send("user")
Send("{TAB}")
Send("pass")
Send("{ENTER}")
with Chrome 70 and other versions :
http://username:password#example.com/yourpage
You can use Java Robot class with Selenium 2 /Selenium WebDriver using Firefox
WebDriver driver = new FirefoxDriver();
driver.get("http://localhost:9990");
WebElement myDynamicElement = driver.findElement(By.id("app"));
Alert alert = driver.switchTo().alert();
try {
Robot robot = new Robot();
alert.sendKeys("username");
robot.keyPress(KeyEvent.VK_TAB);//go to password feild
robot.keyPress(KeyEvent.VK_P);
robot.keyPress(KeyEvent.VK_A);
robot.keyPress(KeyEvent.VK_S);
robot.keyPress(KeyEvent.VK_S);
robot.keyPress(KeyEvent.VK_ENTER);
} catch (AWTException e) {
e.printStackTrace();
}
}
Using Selenium with Robot
http://docs.oracle.com/javase/1.5.0/docs/api/java/awt/Robot.html