簡體   English   中英

Java Jsoup 提交表單

[英]Java Jsoup Submitting a form

我想弄清楚如何使用 Jsoup 提交表單。 在 Xfinity 的網站上,我試圖輸入一個地址並在點擊以下網址中的“顯示交易”后返回結果頁面:

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

這是我當前的代碼:

    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";
}

當前代碼只返回相同的網頁,我如何返回結果頁面?

Jsoup 是一個 HTML 解析器庫,它提供了提取和操作 HTML 頁面數據的功能。 如果需要遍歷網站、提交表單、點擊元素,最好使用其他工具,如seleniumHTTP 客戶端(通常用於 Web 應用程序的自動化測試)或crawler4j等網絡爬蟲庫。

我傾向於不同意 Daniil 的回答,因為 HTTP 客戶端或 crawler4j 都不支持此頁面所需的 javascript。 Selenium 可能是最好的解決方案。

下面是一個如何使用 jsoup 獲取頁面、填寫表單並提交的示例。 結果是 json ,因此您可以將該字符串傳遞給 gson 或類似的。 我並不是說頁面在常規瀏覽器中非常不穩定,有時會捕獲地址輸入,有時會在相同的輸入上嘔吐。

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