如何在Java中使用Selenium访问弹出元素

时间:2017-12-07 13:58:37

标签: javascript java selenium firefox webdriver

我正在尝试使用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中的任何元素时,该元素为null。

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

1 个答案:

答案 0 :(得分:0)

当您在此操作之前调用filter { mutate { add_field => { "file" => "%{[@metadata][s3][key]}"} } else { grok { match => { "file" => "pr:%{NUMBER:pr}-" } } grok { match => { "file" => "author:%{USERNAME:author}-" } } grok { match => { "file" => "platform:%{USERNAME:platform}-" } } } } 时,我们应该为标识为 click() WebDriverWait引导WebElement以正确呈现< strong> getElementById('nav-bar') 并尝试以下操作:

ExpectedConditions.elementToBeClickable