我正在构建一个程序,该程序登录到网站并抓取一些数据。登录表单是一个弹出窗口。因此,我需要访问该www.betexplorer.com网站,在页面的右上角有一个写为“ login”的登录链接。我单击链接,然后出现登录弹出表单。我可以在顶部找到登录链接,但是找不到弹出的登录表单窗口。
我使用了Selinium,在处理JavaScript弹出窗口时应用以下代码时效果很好。
String username = "myUsername"; WebElement element = driver.findElement(By.xpath("the xpath here"));
String realUsername = "arguments[0].setAttribute('value','"+ username"')" ((JavascriptExecutor) driver).executeScript(realUsername, element);
但是我现在正在使用HtmlUnit,之前已经使用过它,而我的其他程序运行良好。
使用HtmlUnit,我发现了一个代码,可在处理JavaScript弹出窗口时提供帮助。我正在尝试使用WebWindowListener,但似乎无法弄清楚。
有人可以帮忙吗?
我的代码段如下:
public class ExplorerHtmlUnit {
public static void main(String[] args) throws Throwable {
WebClient webClient;
webClient = new WebClient();
webClient = new WebClient(BrowserVersion.CHROME);
webClient.getOptions().setThrowExceptionOnScriptError(false);webClient.getOptions().setJavaScriptEnabled(true);java.util.logging.Logger.getLogger("com.gargoylesoftware").setLevel(java.util.logging.Level.OFF);
HtmlPage explorerPage = webClient.getPage("https://www.betexplorer.com");
System.out.println("Explorer Website Found");
List<DomElement> loginClick =
explorerPage.getByXPath("//a[@class='clientmenu__item__in js-window-trigger'][contains(text(),'Login')]");
for (DomElement myele : loginClick)
if(myele.getAttribute("class").equals("login")) {
myele.click();
}
}
System.out.println("login link found and clicked");
//sleep for 5 seconds for javascript form to load
Thread.sleep(5000);
LinkedList<WebWindow> windows = new LinkedList<WebWindow>();
webClient.addWebWindowListener(new WebWindowListener() {
public void webWindowOpened(WebWindowEvent event) {
windows.add(event.getWebWindow());
}
@Override
public void webWindowClosed(WebWindowEvent arg0) { }
@Override
public void webWindowContentChanged(WebWindowEvent arg0)
{ }
});
WebWindow latestWindow = windows.getLast();
HtmlPage popUpPage = (HtmlPage) latestWindow.getEnclosedPage();
HtmlTextInput submitUsername = (HtmlTextInput) popUpPage.getByXPath("//input[@id='login_nick']");submitUsername.setValueAttribute("username");
System.out.println("UserName Found And Entered");
HtmlPasswordInput submitPassword = (HtmlPasswordInput) popUpPage.getByXPath("//input[@id='login_nick']");submitPassword.setValueAttribute("password");
System.out.println("Password Found And Entered");
HtmlButton loginButton = (HtmlButton) popUpPage.getByXPath("//html[1]/body[1]/div[6]/div[1]/div[1]/div[1]/div[1]/form[1]/div[1]/div[3]/button[1]");
loginButton.click();
System.out.println("Login Button Found And Clicked");
webClient.close();
}
}