Selenium/WebView 获取被点击的元素

2 java selenium

是否可以使用WebDriverSelenium 中的类打开浏览器并获取用户单击的元素?

我已经浏览了 selenium 的文档,但没有发现任何有用的东西。

我已经考虑过在网页中插入一个 javascript 函数,每当单击可点击元素时就会调用该函数,但我不知道如何将该信息检索到我的 java 程序中。关于如何解决这个问题有什么想法吗?

小智 5

根据 Saurabh Gaur 给我的提示设法解决了这个问题

这是我用来测试应用程序的 HTML 文档,其名称为Index.html

<html>
<head>
    <title>I am the title, haha!</title>
</head>
<body>
    <p id="id1">I am id1</p>
    <a href="www.google.com" id="ihatejava">end my suffering</a>
<body>
</html>
Run Code Online (Sandbox Code Playgroud)

这是我的java代码。它所做的只是向 HTML 元素添加一个监听器:

public class Main extends Application {

public static void main(String[] args) {
    launch(args);
}

@Override
public void start(Stage stage) throws MalformedURLException {
    WebView webView = new WebView();
    WebEngine engine = webView.getEngine();
    engine.load(new File("PATH/TO/Index.html").toURI().toURL().toExternalForm());

    Scene scene = new Scene(webView);
    stage.setScene(scene);
    stage.show();

    //we need this to check if the document has finished loading, otherwise it would be null and throw a exception
    engine.getLoadWorker().stateProperty().addListener((obs, oldState, currentState) -> {
        if (currentState == State.SUCCEEDED) {
            Document doc = engine.getDocument();
            addListeners(doc);
        }
    });
}

private void addListeners(Document doc) {
    Element link1 = doc.getElementById("id1");
    ((EventTarget) link1).addEventListener("click", e -> {
        System.out.println("id1 was clicked!");
    }, false);

    Element link2 = doc.getElementById("ihatejava");
    ((EventTarget) link2).addEventListener("click", e -> {
        System.out.println("ihatejava was clicked!");
    }, false);
}
}
Run Code Online (Sandbox Code Playgroud)