java/selenium - 如何单击主页顶部弹出的表单中的元素?

标签 java selenium xpath

在我的自动化项目中的某个时刻,我必须单击一个元素,该元素是弹出在主页顶部的表单的一部分(它不会像悬停在某个元素然后消失)成功访问页面并单击弹出表单的元素后。

我一直在尝试其他问题的评论中建议的各种解决方案,例如使用偏移量和等待元素变得可点击,但没有一个对我有用。

这是第一个字段“Name”当前状态的代码:

try {
                System.out.println("Filling in mandatory fields of the contact form... ");
                wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//div[@id='jcemediabox-popup-frame']")));

                System.out.println("Filling in name... ");
                wait.until(ExpectedConditions.elementToBeClickable(By.xpath("(//div[@class='formBody']/input)[1]")));
                WebElement nameField = driver.findElement(By.xpath("(//div[@class='formBody']/input)[1]"));
                actions.moveToElement(nameField).build().perform();
                actions.moveByOffset(5, 5).build().perform();
                nameField.sendKeys(contactInput[1]);
                nameField.submit();
                System.out.println("Filled in name");

            } catch (Exception e) {
                System.out.println("Could not complete actions on: contact form");
                e.printStackTrace();
            }

编辑 - 工作代码(感谢 segalaj):

try {
                System.out.println("Filling in mandatory fields of the contact form... ");
                wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//iframe[@id='jcemediabox-popup-iframe']")));
                driver.switchTo().frame(driver.findElement(By.xpath("//iframe[@id='jcemediabox-popup-iframe']")));

                driver.wait(pauseInSeconds);

                System.out.println("Filling in name... ");
                wait.until(ExpectedConditions.elementToBeClickable(By.name("form[Name]")));
                driver.findElement(By.name("form[Name]")).sendKeys(contactInput[0]);
                System.out.println("Filled in name");

                driver.wait(shorterWait);               

                driver.switchTo().defaultContent();             

            } catch (Exception e) {
                System.out.println("Could not complete actions on: contact form");
                e.printStackTrace();
            }

最佳答案

由于您的弹出窗口位于 iframe 中,因此您需要告诉 Webdriver 切换到 iframe:

<webdriver>.switchTo().frame(<iframe-webelement>);

然后您将能够访问 iframe 元素。
完成框架后,不要忘记返回主页。

您可以找到文档 here

希望有帮助。

关于java/selenium - 如何单击主页顶部弹出的表单中的元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30167261/

相关文章:

java - DefaultTableModel 不显示列

java - 对敏感数据使用 startActivityForResult() 是否安全?

Java:clone() 和相等性检查

Python/Scrapy/Selenium/PhantomJs - 性能

javascript - 如何为 before::和 after::之间的文本编写定位器

Java LinkedList 迭代时删除的最安全方法

JavaFX 线程卡住

python - 遍历 Selenium 2 WebDriver 中的表(python)

xml - Powershell选择XML节点,其中属性包含在数组中

bash - 以非递归方式列出可用标签的 XPath(在 shell 脚本中使用 xmllint)