Selenium:如何点击JavaScript按钮

4
我需要编写一些脚本来自动测试用Flex/AMF技术构建的Web应用程序的加载时间。测试包括打开IE浏览器,浏览多个选项卡,并测量从点击最后一个选项卡到加载页面内容所需的时间,然后关闭浏览器。
我使用Selenium Web Driver和Junit在Java中编写了一个小脚本,打开IE窗口,输入登录名和密码。但是我在“点击”登录按钮时遇到了问题。
首先,我尝试通过findElement和By.partiallinktext查找和点击按钮,但Selenium告诉我:“无法找到部分链接文本的元素”(在该站点上ctrl+f可以正常工作)。
我尝试了使用moveByOffset鼠标单击以及按下按钮(Robot类-填写密码后按“tab”和“enter”)。它们都不起作用。
接下来,我找到了JavascriptExecutor - 我认为它可能是解决我的问题的答案,但我应该如何使用这个类?
该站点上的按钮:
<button style="width: 120px;" onclick="javascript:logIn();"> Login </button>

我的Java代码:

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

我在测试方面经验不多,所以非常感谢您的帮助。

2个回答

4
不要使用JavaScript。试试这个:
String xPath = "//button[contains(.,'Login')]";
driver.findElement(By.xpath(xPath))).click();

更好的选择,但未经测试:
// 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();

请注意,https://sqa.stackexchange.com/ 上有关于Selenium等技术的信息。

3
根据您分享的HTML,在所需元素上调用click(),您可以使用以下解决方案:
driver.findElement(By.xpath("//button[normalize-space()='Login']")).click();

从另一个角度来看,所需的元素需要启用JavaScript,在这种情况下,您需要使用WebDriverWait等待元素可被单击,并可以使用以下解决方案:

new WebDriverWait(driver, 20).until(ExpectedConditions.elementToBeClickable(By.xpath("//button[normalize-space()='Login']"))).click();

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接