【问题标题】:How to access popup elements using Selenium in Java如何在 Java 中使用 Selenium 访问弹出元素
【发布时间】:2017-12-07 13:58:36
【问题描述】:

我正在尝试使用 java 中的 selenium 从弹出窗口/警报中获取和访问元素。代码如下:

import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;

public class Test {


public static void main(String[] args) throws InterruptedException {

    System.setProperty("webdriver.gecko.driver", "path_to_gecko_driver");

    FirefoxDriver firefoxDriver = new FirefoxDriver();

    firefoxDriver.get("some_url_which_needs_webcam_and_microphone");        
    WebElement element = new WebDriverWait(firefoxDriver, 20).until(ExpectedConditions.presenceOfElementLocated(new By.ByClassName("button_id")));
    element.click();

    JavascriptExecutor js = (JavascriptExecutor) firefoxDriver;
    String title = String.valueOf(js.executeScript("return document.title"));

    System.out.println("Title ==== " + title);

    Object rezult = js.executeScript("return document.getElementById(\'nav-bar\')");
    System.out.println("Browser element ==== " + rezult); //===>null

    System.out.println("FINISH");

    }
}

我正在尝试访问浏览器弹出元素,因此我可以在可用的网络摄像头或麦克风之间进行选择,并允许或拒绝访问。 JS 代码在浏览器的控制台中运行良好,但在 Java 中却不行。

每当我尝试使用 JavascriptExecutor 访问 Java 中的任何元素时,该元素都是空的。

如何使用 Java 中的 JavascriptExecutor 访问弹出元素?是否有任何其他预定义配置或我缺少的任何其他先决条件?谢谢

【问题讨论】:

  • 你到底卡在哪里了?在哪一行?错误说明了什么?使用错误堆栈跟踪更新问题。
  • 这个:js.executeScript("return document.getElementById(\'nav-bar\')");在 Java 中编译时结果为 null,而不是在浏览器控制台中。这也是一个浏览器元素
  • 浏览器可以使用alert类来处理alert
  • @Ankur。我已经这样做了。结果也是null
  • 我正在使用带有 selenium-java 3.8.1 的 Maven 项目

标签: javascript java selenium firefox webdriver


【解决方案1】:

当您在此操作之前调用 click() 时,我们应该为标识为 getElementById('nav-bar')WebDriverWait 诱导 WebDriverWait 以通过 ExpectedConditions.elementToBeClickable 正确呈现> 并尝试以下方法:

js.executeScript("return document.getElementById('nav-bar')");

【讨论】:

  • 我也已经这样做了,我已经避开了“'”字符,因为我认为这可能是问题所在。谢谢
猜你喜欢
  • 1970-01-01
  • 2020-09-08
  • 1970-01-01
  • 1970-01-01
  • 2016-01-05
  • 2021-03-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多