Java selenium click override or create own - java

Hei. I have been creating automated tests with selenium, but I have ran into some issues with IE the click not working. (Seems like a common issue where the driver just freezes and it won't timeout or anything).
As a workaround I created a method which uses javascript executor to do the click instead.
public static void IEClick(WebElement element) {
JavascriptExecutor executor = (JavascriptExecutor) driver;
executor.executeScript("arguments[0].click();", element);
}
The issue I have is that I would have to rewrite all my tests in order to make them work on IE.
#Test
public void Simpletest(){
Frontpage.SearchBox.sendKeys("DeadPool");
Frontpage.GOButton.click();
Frontpage.FirstREsult.click();
}
Would have to be changed to
#Test
public void Simpletest(){
Frontpage.SearchBox.sendKeys("DeadPool");
IEClick(Frontpage.GOButton);
IEClick(Frontpage.FirstREsult);
}
This is a solution but this mean I would have to redo all my tests to handle this. Which seems a little too much. So I'm wondering is it possible to create my own click?
Desired solution
Frontpage.FirstREsult.MyClick();
Where in MyClick I have already handled all the cases with different browsers etc.So I could just search and replace the click with my own click.

1) At first you can get a browser name from capabilities and using js or native click depending on browser
Capabilities caps = ((RemoteWebDriver) driver).getCapabilities();
String browserName = caps.getBrowserName();
2) Also you can always use a js click. It's a very rare situation where you can need the native one

Related

Selenide and bonigarcia

I'm trying to use Selenide and bonigarcia together with using multiple web driver, such as Chrome, Mozilla, Edge and etc.
This is what I've done:
public static Selenide driver;
public static void runBrowser(String browserName, String url) throws Exception {
if(browserName.equals("Chrome")) {
WebDriverManager.chromedriver().browserVersion(browserConfiguration.chromeVersion).setup();
Configuration.startMaximized = true;
driver.open(url);
}
else if(browserName.equals("Firefox")) {
WebDriverManager.firefoxdriver().browserVersion(browserConfiguration.firefoxVersion).setup();
Selenide.open(url);
}
else if(browserName.equals("Edge")) {
WebDriverManager.edgedriver().browserVersion(browserConfiguration.edgeVersion).setup();
driver.open(url);
} else {
throw new Exception("Something went wrong opening browser");
}
}
But, when I am trying to call that method with the parameter of "Firefox" or "Edge", it always runs on chrome. So, every time when I call that method, chromes web driver is running.
I've made it with Selenium, the difference between them is that instead of Selenide.open(url), I use WebDriver.get(url) and it works fine when I call a method with "Firefox" or "Edge" parameter.
Any ideas?
**EDIT: **
I added Configuration.browser = FirefoxDriverFactory.class.getName(); and now it looks like that: WebDriverManager.firefoxdriver().browserVersion(browserConfiguration.firefoxVersion).setup(); Configuration.browser = FirefoxDriverFactory.class.getName(); Selenide.open(url);
It will open any browser which I want, Chrome, Mozilla, Edge, etc.
But, somehow, I don't think that this is a real solution. I don't even know what have I done with adding FirefoxDriverFactory.class.getName() and why it is working now.
Selenide already includes WebDriverManager from bonigarcia.
You can just choose the browser either with
Configuration.browser = "firefox";
or setting SystemProperty selenide.browser, e.g. -Dselenide.browser=firefox
You don't need any Factories, WebDriverManager calls etc.

Wait for page to be loaded with HtmlUnitDriver

I have several tests that run with Selenium and HtmlUnitDriver. Sometimes when I run them and want to click on an element or read text, the elements can not be found. Every time a Exception is thrown I save the Code of the Page for debugging purposes. But when I check the Code, the element is there and when I rerun the test everything works fine.
My guess is that the page was not completely loaded when I try to access the element.
So I would like to wait until Selenium has finished loading the page before I try to access elements.
I fond two ways to achieve it:
Execute Javascript (e.g. window.initComplete) and wait for the result to be true. The problem: In Selenium I have to have an instance of JavascriptExecuter but HtmlUnitDriver is not derived from that class and I cannot switch to FirefoxDriver (which implements the JavascriptExecuter interface) because we are running the tests headless.
Wait for the last element on the page to load
The problem with this approach is that the page is based on our framework and if that changes and suddenly there are different elements on the bottom of the page I have to adapt every test.
Any suggestions on how to approach the problem?
You can create a custom ExpectedCondition:
public static ExpectedCondition<Boolean> waitForLoad() {
return new ExpectedCondition<Boolean>() {
#Override
public Boolean apply(WebDriver driver) {
return ((JavascriptExecutor) driver).executeScript("return document.readyState").equals("complete");
}
};
}

While working with Selenium WebDriver and Java I am not able to use click() function of WebDriver (giving no exception)

I have set the following properties:-
Set environment variables JAVA_HOME,path,ANT_HOME,path (using JDK version --> jdk1.7.0_40)
In Eclipse set the system Library, added all needed jars and select all jars in Order and Export.
Install the Firefox Version 24 and used the Selenium jar(selenium-server-standalone-2.41.0).
Giving no error while running the Java application, also no exception while not able to click on particular element.
sendKeys(Keys.ENTER) is working fine, but instead I need to use click() method.
Also code is working fine on other systems, I think I am missing something.
click() method is not giving any valid response, it makes me feel like its only declared not defined. I have tried on different websites, on different elements and with different types(xpath, css selector, name, id) but nothing worked for me. I took focus on that element by webdriver and also by highlighting the element using javascript code, its showing that particular element is present. I have performed other operations like entering username after clicking on that element, its performing well. I have worked with different browsers, different webpages also maximize the window using selenium but no positive response.
Any help will appreciate.
Thanks in advance
Hi the snippet below worked fine for me
public static void main(String[]args){
WebDriver appDriver;
appDriver = new FirefoxDriver();
appDriver.get("https://web210.qa.drfirst.com/login.jsp");
WebElement loginButton = appDriver.findElement(By.className("btn"));
loginButton.click();
appDriver.switchTo().alert().accept();
appDriver.close();
}

Selenium WebDriver mouse actions moveToElement doesn't raise mouseout event on Firefox Linux

I have been trying to test a tooltip in my web page using Selenium WebDriver with Firefox 19.
I'm basically trying to use mouse actions to hover over the element that has the tooltip attached in order to test that the tooltip is displayed and to hover over another element to test that the tooltip is hidden.
The first operation works fine but when hovering over another element the tooltip remains visible. This issue does not occur when testing the webpage manually.
Has anyone else encountered this issue before? I'm using Ubuntu 12.04.
It seems that the Advanced Actions API relies on native events, which are disabled in the Linux version of Firefox by default. Therefore, they must be enabled in the WebDriver instance explicitly.
FirefoxProfile profile = new FirefoxProfile();
//explicitly enable native events(this is mandatory on Linux system, since they
//are not enabled by default
profile.setEnableNativeEvents(true);
WebDriver driver = new FirefoxDriver(profile);
Also, in my case I needed to upgrade the WebDriver to version 2.31 since the hover(moveToElement) action did not work properly on 2.30 even with native events explicitly enabled. Tested this with version 2.31 of WebDriver and versions 17 and 19 of Firefox on Linux.
For more information you may check this link:
http://code.google.com/p/selenium/wiki/AdvancedUserInteractions#Native_events_versus_synthetic_events
I also run into this problem with Selenium 2.30 on Firefox 19. It works fine on FF 18.2.
This is a simple but handy method with a javascript call that will send a mouseout() event to whichever element you specify (I prefer to pass them using By but you can change this to whatever you like.
I had a problem with Chrome where tooltips were refusing to close once clicked and obscured other nearby click events causing them to fail. This method saved the day in that case. Hope it helps someone else!
/**
* We need this to close help text after selenium clicks
* (otherwise they hang around and block other events)
*
* #param by
* #throws Exception
*/
public void javascript_mouseout(By by) throws Exception {
for (int i=0; i<10; i++) {
try {
JavascriptExecutor js = (JavascriptExecutor)driver;
WebElement element = driver.findElement(by);
js.executeScript("$(arguments[0]).mouseout();", element);
return;
} catch (StaleElementReferenceException e) {
// just catch and continue
} catch (NoSuchElementException e1) {
// just catch and continue
}
}
}
You can call it after any sort of click() event like this:
By by_analysesButton = By.cssSelector("[data-section='Analyses']");
javascript_mouseout(by_analysesButton);
Fyi, mine tries 10x via the for loop with the try/catches because our app has a tendency with Chrome towards stale element exceptions, so if you don't have this problem the method can be pared down considerably.
I had the same problem.
At first I used the method moveToElement() without perform().
Then I added Firefox Profile with setEnableNativeEvents, but it still didn't work for me.
Finally I solved this issue in this way (simply by adding perform():
WebElement username = driver.findElement(By.id("username"));
Actions actions = new Actions(driver);
actions.moveToElement(username).perform();
WebElement tooltip = driver.findElement(By.id("tooltip"));
tooltip.isDisplayed();
and it works fine.

The screen is not navigating even the click() method is executed successfully in mobile web app using selenium web driver

I was trying to click a button on my mobile web app, using selenium web driver. The button is located, the text over the button can be derived and even the click event is performing well. But the navigation doesn't occur.
I tried with Click() method, sendKeys() method and also with script executor. But couldn't process further on.
CODE:
public class TestWeb
{
WebDriver driver;
private Selenium selenium;
#Before
public void setUp() throws Exception {
driver = new IPhoneDriver();
driver.get("http://10.5.95.25/mobilebanking");
}
#Test
public void TC() throws Exception {
System.out.println("page 1");
Thread.sleep(5000);
WebElement editbtn1 = driver.findElement(By.id("ext-comp-1018"));
String s1 = editbtn1.getText();
System.out.println(s1);
editbtn1.click();
editbtn1.sendKeys(Keys.ENTER);
((JavascriptExecutor)driver).executeScript("arguments[0].click;", editbtn1);
System.out.println("ok");
}
#After
public void tearDown() throws Exception {
System.out.println("*******Execution Over***********");
}
}
I tried click, sendKeys and ScriptExecutor separately and also combined. It is executing without any error but the navigation doesn't occur.
Does anybody can help me with some other ways to perform click function on the button?
Ram
This may not be your issue but I noticed "ext-comp-" and guess you are using extjs.
I'm using GXT and while finding by id worked for many things, on some submit buttons it didn't.
I had to use firebug in firefox to locate the element and copy the xpath.
Then I could click the element by
driver.findElement(By.xpath("//div[#id='LOGIN_SUBMIT']/div/table/tbody/tr[2]/td[2]/div/div/table/tbody/tr/td/div")).click(); // worked
It was failing silently for me too. My submit button has the id of LOGIN_SUBMIT so I don't know why the following failed but ....
driver.findElement(By.id("LOGIN_SUBMIT")).click();//failed
Edit:
Here is an exact example (case 1 of 2):
WebDriverWait wait = new WebDriverWait(driver, 30);
wait.until(ExpectedConditions.elementToBeClickable(By.xpath("//div[#id='gwt-debug-LOGIN_SUBMIT']")));
//wait.until(ExpectedConditions.elementToBeClickable((By.id("gwt-debug-LOGIN_SUBMIT")))); <!-- id works as well
OK so the element is found. It will timeout and throw an exception if it is not.
Still, the following fails (under firefox, works with chrome) with no error and the page does not navigate.
driver.findElement(By.xpath("//div[#id='gwt-debug-LOGIN_SUBMIT']")).click();
//driver.findElement(By.id("gwt-debug-LOGIN_SUBMIT")).click(); <-- fails too
What I have to do is:
driver.findElement(By.xpath("//div[#id='gwt-debug-LOGIN_SUBMIT']/div/table/tbody/tr[2]/td[2]/div/div/table/tbody/tr/td/div")).click();
So my experience was that even if I found the element with xpath, clicking failed unless I used a complete xpath.
Here is another exact example (case 2 of 2):
I can find an element like so:
WebElement we = driver.findElement(By.xpath("//*[#id=\"text" + i + "\"]"));
I know I have found it because I can see the text via:
we.getText();
Still selecting by the path I found it fails.
//get outta town man the following fails
driver.findElement(By.xpath("//*[#id=\"text" + i + "\"]")).click();
In this case there is not more explicit xpath to try as in case 1
What I had to do was use css:
//bingo baby works fine
driver.findElement(By.cssSelector("div#text" + i + ".myChoices")).click();
Actually, I obtained the css path via firebug than shortened it.
//this is what I recieved
html.ext-strict body.ext-gecko div#x-auto-0.x-component div#x-auto-1.x-component div#x-auto-3..myBlank div#choicePanel1.myBlank div.x-box-inner div#text3.myChoices //text3 is the id of the element I wanted to select
Whether or not you can figure out your needed xpaths and css selectors, I don't know, but I believe I experienced exactly what you did.

Categories

Resources