How can I manipulate DOM with Java?

2019-09-16 17:12发布

Is there any way I can get a DOM element and manipulate it so I can put my username and password in order to login automatically, when starting the application? For now, I've used Robot in order to let the computer pass in my login information and login automatically, but I need a better method. Any help is much appreciated!

import java.awt.AWTException;
import java.awt.Desktop;
import java.awt.Robot;
import java.awt.Toolkit;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.StringSelection;
import java.awt.event.KeyEvent;
import java.net.URL;

public class Main
{
private static String OS                = null;
private static Integer CTRL             = null;

private static String username          = "u1240430";
private static String password          = "123123";

public static void main(String[] args) {

    OS = System.getProperty("os.name");
    if( OS.equalsIgnoreCase("MAC OS X") ){
        CTRL = KeyEvent.VK_META;
    }else{
        CTRL = KeyEvent.VK_CONTROL;
    }


    try {
        Desktop.getDesktop().browse(new URL("https://awebsite.something/login.php").toURI());
        startWithLogin();
    } catch (Exception e){
        System.out.println(e.getMessage());
    }
}

private static void startWithLogin() {
    try {
        Robot r = new Robot();

        StringSelection selection = new StringSelection(username);
        Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
        clipboard.setContents(selection, null);

        r.delay(1500);

        r.keyPress(CTRL);
        r.keyPress(KeyEvent.VK_V);

        r.keyRelease(KeyEvent.VK_V);
        r.keyRelease(CTRL);

        r.delay(100);

        r.keyPress(KeyEvent.VK_TAB);
        r.keyRelease(KeyEvent.VK_TAB);

        r.delay(100);

        selection = new StringSelection(password);
        clipboard.setContents(selection, null);

        r.delay(100);

        r.keyPress(CTRL);
        r.keyPress(KeyEvent.VK_V);

        r.keyRelease(KeyEvent.VK_V);
        r.keyRelease(CTRL);

        r.delay(100);

        r.keyPress(KeyEvent.VK_ENTER);
        r.keyRelease(KeyEvent.VK_ENTER);

    } catch (AWTException ex) {
        System.out.println(ex.getMessage());
    }
  }
}

0条回答
登录 后发表回答