Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Selenium: how to click on javascript button

I must write some scripts for automatic tests to check load-time a web application built in flex/amf technology. The test will consist in opening the IE browser, going through several tabs and measuring the time from clicking on the last tab to load the page content and then closing the browser.

I wrote in java a small script with Selenium Web Driver and Junit. Script opening the IE-window, enter login and password. I have problem with 'click on' login-button.

Firstly I have try to find and click button by findingElement and By.partiallinktext, but selenium informed me: "Unable to find element with partial link text" (ctrl+f works fine on that site).

I tried clicking using moveByOffset mouse and by pressing buttons (class Robot - 'tab' and 'enter' after fill string with password). All of them doesn't work.

Next I found JavascriptExecutor - I thing, that it could be answer for my problem, but how I should use this class?

Button on that site:

<button style="width: 120px;" onclick="javascript:logIn();"> Login </button>

My java code:

WebElement button = driver.findElement(By.partialLinkText("Login")); 
JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript ("document.getElementByText(\"Login\")).click();", button); 

I haven't a lot of experience with tests, so I will be grateful for your help.

like image 754
Lukas Avatar asked Mar 05 '23 09:03

Lukas


2 Answers

Don't go through JavaScript. Try this:

String xPath = "//button[contains(.,'Login')]";
driver.findElement(By.xpath(xPath))).click();

Better yet, but not tested:

// xPath to find a button whose text() (ie title) contains the word Login
String xPath = "//button[contains(text(),'Login')]";
driver.findElement(By.xpath(xPath))).click();

Please also note that https://sqa.stackexchange.com/ has info on Selenium (etc.)

like image 130
Stefan Avatar answered Mar 15 '23 00:03

Stefan


As per the HTML you have shared to invoke click() on the desired element you can use the following solution:

driver.findElement(By.xpath("//button[normalize-space()='Login']")).click();

On another perspective the desired element looks JavaScript enabled and that case you have to induce WebDriverWait for the element to be clickable and you can use the following solution:

new WebDriverWait(driver, 20).until(ExpectedConditions.elementToBeClickable(By.xpath("//button[normalize-space()='Login']"))).click();
like image 44
undetected Selenium Avatar answered Mar 15 '23 01:03

undetected Selenium