【发布时间】:2021-06-03 20:01:26
【问题描述】:
我正在尝试使用 htmlunit 抓取捐赠页面。我需要填写昵称、消息、金额等输入,然后选择付款方式以打印付款网址。填写文本输入没有问题,但是当我尝试选择单选按钮(付款方式)时,它不起作用。它只是让默认按钮处于选中状态。
页面:https://tipo.live/p/bartlomiej-skowron(波兰语)
我的代码:
WebClient webClient = new WebClient(BrowserVersion.CHROME);
webClient.getOptions().setCssEnabled(false);
webClient.getOptions().setJavaScriptEnabled(true);
webClient.getOptions().setThrowExceptionOnScriptError(false);
webClient.getOptions().setThrowExceptionOnFailingStatusCode(false);
webClient.getOptions().setPrintContentOnFailingStatusCode(false);
WebRequest request = new WebRequest(new URL("https://tipo.live/p/bartlomiej-skowron"));
HtmlPage page = webClient.getPage(request);
webClient.waitForBackgroundJavaScript(2000);
JavaScriptJobManager manager = page.getEnclosingWindow().getJobManager();
HtmlForm form = page.getForms().get(0);
HtmlButton button = (HtmlButton)form.getElementsByTagName("BUTTON").get(0);
HtmlTextInput username = form.getInputByName("username");
HtmlTextArea message = form.getTextAreaByName("message");
HtmlTextInput amount = form.getInputByName("amount");
HtmlInput payment = form.getInputByValue("7"); //radio button
username.type("Nickname");
message.type("Example Message");
amount.type("25");
payment.setChecked(true); // it doesnt work
webClient.waitForBackgroundJavaScript(500);
button.click();
while(true){
if (manager.getJobCount() <= 0) break;
}
HtmlPage currentPage = (HtmlPage) webClient.getCurrentWindow().getEnclosedPage();
System.out.println(currentPage.getUrl());
我也尝试过执行 javascript,但它也不起作用:
WebRequest request = new WebRequest(new URL("https://tipo.live/p/bartlomiej-skowron"));
HtmlPage page = webClient.getPage(request);
page.executeJavaScript("document.getElementById(\"7__input\").click();");
page.executeJavaScript("document.getElementsByName(\"amount\")[0].value=\"25\";");
page.executeJavaScript("document.getElementsByName(\"message\")[0].value=\"Example Message\";");
page.executeJavaScript("document.getElementsByName(\"username\")[0].value=\"Nickname\";");
page.executeJavaScript("document.getElementsByClassName(\"octf-btn octf-btn-primary octf-btn-icon\")[0].click();");
【问题讨论】:
标签: javascript java forms web-scraping htmlunit