首先是规范,我正在用 java 编写 Selenium Webdriver 测试,用于主要用 ExtJS 编写并在 firefox 浏览器 v14 上运行的应用程序。有趣的是,Selenium 可以找到我想要单击的元素,但单击似乎没有被执行,或者即使执行了,也没有发生所需的结果(出现弹出窗口)。我还在 Selenium IDE 中验证了我正在寻找的元素(我通过 Xpath 定位的 span 元素)存在,但在 Selenium IDE 中我遇到了无法单击它的相同问题。
如果我手动单击该按钮,则会出现弹出窗口,询问我要上传什么文件。我还尝试了其他元素,例如 span 的父“button”元素、父“em”元素和父“div”元素,但都没有成功。
让我丧命的是,我几周来一直在为这个应用程序编写 Selenium 测试,并且总是能够使用这种方法来单击按钮,而对于这个特定的按钮,它不再起作用。
WebElement uploadButton = driver.findElement(By.xpath("//span[contains(text(), 'Upload Popup')]"));
uploadButton.click();
编辑1:认为按钮本身的代码可能有帮助
<button id="filefield-1158-buttonEl-btnEl" class="x-btn-center" autocomplete="off" role="button" hidefocus="true" type="button" style="background-color: transparent;">
注意id是ExtJS创建的动态id
最佳答案
这可能有很多原因。我建议您在测试运行时进行调试。
可以在您的 Selenium Firefox 实例中安装 FireBug:
File file = new File("firebug-1.8.1.xpi");
FirefoxProfile firefoxProfile = new FirefoxProfile();
firefoxProfile.addExtension(file);
firefoxProfile.setPreference("extensions.firebug.currentVersion", "1.8.1"); // Avoid startup screen
WebDriver driver = new FirefoxDriver(firefoxProfile);
我假设您可以通过 JUnit(在 Eclipse 之类的 IDE 中)启动测试。在 Debug模式下启动测试并在单击按钮之前设置断点。然后通过 FireBug 检查 html 代码。它可能会给你一个开始。
另一种可能性是通过 css 类 (By.className) 或选择器 (By.cssSelector) 选择按钮:
WebElement uploadButton = driver.findElement(By.className("x-btn-center"));
uploadButton.click();
如果页面上有多个按钮,则必须使用
List<WebElement> buttons = driver.findElements(By.className("x-btn-center"));
WebElement uploadButton = buttons.get(index);
uploadButton.click();
关于java - 使用 selenium webdriver 单击元素不会产生预期结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13995253/