2

Google Calendar我的目标是通过WebEnginein自动登录JavaFX并在WebView. 但我似乎无法将字符串值插入密码字段,即使它与用户名字段完美配合。

我试过用 Java 创建脚本并用Element e = webEngine.getDocument().getElementById(password)插入值e.setAttribute("value","mypassword"),但这也不起作用。它没有提供任何堆栈跟踪,这意味着该元素存在,但我无法以某种方式插入该值。

    System.setProperty("sun.net.http.allowRestrictedHeaders", "true");
    WebEngine webEngine = webView.getEngine();
    webEngine.load("https://calendar.google.com");
    webEngine.getLoadWorker().stateProperty().addListener(
         new ChangeListener<State>() {
               @Override
               public void changed(ObservableValue ov, State oldState, State newState) {
               if (newState == State.SUCCEEDED) {
                      webEngine.executeScript(
                            "function login(user){"
                          + " var usernameField = document.getElementById(\"identifierId\");"
                          + " usernameField.value = user;"
                          + " var sButton = document.getElementById(\"identifierNext\");"
                          + " sButton.click();"
                          + "}"
                          + "login('myusername');"
                       );
                }
        }
    });
    Thread t = new Thread(() -> {
            try {
                Thread.sleep(5000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            Platform.runLater( () -> {
                webEngine.executeScript(
                    "function login(pass){"
                            + " var passwordField = document.getElementById(\"password\");"
                            + " passwordField.value = pass;"
                            + " var sButton = document.getElementById(\"passwordNext\");"
                            + " sButton.click();"
                            + "}"
                            + "login('mypassword');"
             );
         });
    });
    t.start();

结果应该是,侦听器等待页面加载,然后填写用户名并单击下一步。然后线程开始但等待 5 秒以确保单击下一个,然后它应该填写密码凭据但没有。

4

1 回答 1

0

使用"document.querySelector(\"#password > div.aCsJod.oJeWuf > div > div.Xb9hP > input\");"而不是document.getElementById(\"password\");查找密码字段。

于 2019-07-23T12:30:31.920 回答