适合JavaHTMLUnit的简单表单

knsnq2tg  于 2021-07-03  发布在  Java
关注(0)|答案(1)|浏览(350)

所以我试着访问这个网站,并填写样本表格。手动操作后,网页会将我重定向到地址如下的网站:http://wklejto.pl/[number],在下面的代码中我要做的是:
用形式写东西。
提交。
获取上传文本的网页地址。

import com.gargoylesoftware.htmlunit.BrowserVersion;
import com.gargoylesoftware.htmlunit.WebClient;
import com.gargoylesoftware.htmlunit.html.*;

public class Main{
    public static void main(String[] args) throws Exception {
        java.util.logging.Logger.getLogger("com.gargoylesoftware").setLevel(java.util.logging.Level.OFF);
        WebClient webClient=new WebClient(BrowserVersion.CHROME);
        webClient.getOptions().setUseInsecureSSL(true);
        HtmlPage page=webClient.getPage("http://wklejto.pl/");
        HtmlElement samp=page.getElementByName("source20201129");//IT's updating daily in form: "source" + year + month + day
        HtmlForm form=page.getHtmlElementById("formwyslij");
        HtmlElement submit=form.getInputByName("submit");
        samp.click(); samp.type("It's Working"); submit.click();
        webClient.waitForBackgroundJavaScript(1000);
        page=(HtmlPage) webClient.getCurrentWindow().getEnclosedPage();
        System.out.println(page.getUrl());
        webClient.close();
    }
}

运行此代码后,system.out.println()将打印:

http://wklejto.pl/index.php

而不是我所期待的:

http://wklejto.pl/[number of uploaded text]

是虫子吗?我做错什么了?

7vux5j2d

7vux5j2d1#

看到了吗https://github.com/htmlunit/htmlunit/issues/272
一开始,我认为如果某些东西不起作用,那么禁用日志记录不是一个好主意——也许日志中有一个提示可以帮助您解决问题。
我们已经做了一些测试,似乎有一些js处理程序附加到textarea,需要在click进程正确完成之前完成。
这段代码对我很有用(也许你需要根据你的机器增加等待时间)

WebClient webClient=new WebClient(BrowserVersion.CHROME);
    webClient.getOptions().setUseInsecureSSL(true);

    HtmlPage page=webClient.getPage("http://wklejto.pl/");

    //IT's updating daily in form: "source" + year + month + day
    HtmlElement samp=page.getElementByName("source20201205");
    HtmlForm form=page.getHtmlElementById("formwyslij");
    HtmlElement submit=form.getInputByName("submit");

    // samp.click(); // no need to click, type triggers the required focus events
    samp.type("It's Working");
     // wait a bit to let the textarea onkey handler do there magic
    webClient.waitForBackgroundJavaScript(4_000);

    submit.click();
    webClient.waitForBackgroundJavaScript(1_000);

    // get the current page from the window
    page=(HtmlPage) webClient.getCurrentWindow().getEnclosedPage();
    System.out.println(page.getUrl());

    webClient.close();

相关问题