简体   繁体   English

Java Jsoup 提交表单

[英]Java Jsoup Submitting a form

I am trying to figure out how to submit a form using Jsoup.我想弄清楚如何使用 Jsoup 提交表单。 On Xfinity's website, I am trying to input an address and get back the resulting page after clicking on "Show me deals" from the url below:在 Xfinity 的网站上,我试图输入一个地址并在点击以下网址中的“显示交易”后返回结果页面:

https://www.xfinity.com/learn/offers https://www.xfinity.com/learn/offers

Here is my current code:这是我当前的代码:

    public String getISP() throws IOException {
    Connection.Response addressFormResponse = Jsoup.connect("https://www.xfinity.com/learn/offers")
            .data("Address.SingleStreetAddress", address)
            .method(Connection.Method.POST)
            .execute();

    Document doc = addressFormResponse.parse();

    System.out.println(doc.title());
    System.out.println(doc.location());
    if (doc.location().contains("Active Address")) {
        return "Comcast XFinity";
    }
    return "Cannot find an ISP";
}

The current code only returns the same webpage, how would I get back the resulting page?当前代码只返回相同的网页,我如何返回结果页面?

Jsoup is a HTML parser library, it provides functionality for extracting and manipulating data on HTML page. Jsoup 是一个 HTML 解析器库,它提供了提取和操作 HTML 页面数据的功能。 If you need traverse websites, submit forms, click elements, it's better to use another tools, like selenium , HTTP client (which are often used for automated test of web applications) or web crawler libraries like crawler4j .如果需要遍历网站、提交表单、点击元素,最好使用其他工具,如seleniumHTTP 客户端(通常用于 Web 应用程序的自动化测试)或crawler4j等网络爬虫库。

I would tend to disagree with Daniil's answer in that neither HTTP Client or crawler4j support javascript which is required for this page.我倾向于不同意 Daniil 的回答,因为 HTTP 客户端或 crawler4j 都不支持此页面所需的 javascript。 Selenium is probably the best solution. Selenium 可能是最好的解决方案。

What follows is an example of how to use jsoup to fetch a page, fill out a form, and submit it.下面是一个如何使用 jsoup 获取页面、填写表单并提交的示例。 The result is json and so you would then pass that string to gson or similar.结果是 json ,因此您可以将该字符串传递给 gson 或类似的。 I did not that the page was very flaky just in a regular browser, and sometimes would catch the address input and sometimes would barf on the same input.我并不是说页面在常规浏览器中非常不稳定,有时会捕获地址输入,有时会在相同的输入上呕吐。

Document doc = Jsoup.connect("https://www.xfinity.com/learn/offers").get();
FormElement form = (FormElement) doc.selectFirst("[data-form-dealfinder-localization]");
Element input = form.selectFirst("#Address_StreetAddress");
input.val("2000 YALE AVE E, SEATTLE, WA 98102");
String json = form.submit().ignoreContentType(true).execute().body();

System.out.println(json);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM