问题
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.
回答1:
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.)
回答2:
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();
来源:https://stackoverflow.com/questions/52405456/selenium-how-to-click-on-javascript-button