簡體   English   中英

使用Jsoup獲取表單中的所有名稱 - 值對

[英]Obtaining all name-value pairs in a form using Jsoup

我想使用Jsoup和HttpClient自動發布大量HTML表單。 這些表單中的大多數都有隱藏字段(使用會話ID等)或具有默認值,我寧願單獨留下。

單獨編寫每個表單提交 - 從頁面中提取每個隱藏或默認值 - 非常繁瑣,所以我考慮編寫一個通用方法來獲取給定表單的HTTP參數列表。

然而,這不是一個簡單的代碼片段,因為輸入標簽和字段類型的多樣性,每個都可能需要特定的處理(例如textareas,復選框,單選按鈕,選擇......)所以我想我會首先搜索/詢問,以防它已經存在。

注意:Jsoup和HttpClient是給定的; 我無法改變 - 所以請不要提供建議其他解決方案的答案:我有一個Jsoup Document對象,我需要構建一個HttpClient HttpRequest。

所以我最終寫了它。 我仍然更願意交換經過現場測試的東西(並希望在其他地方進行維護),但萬一它可以幫助任何人降落在這里......

沒有經過全面測試,也沒有對multipar / form-data的支持,但在我嘗試的幾個例子中有效:

  public void submit(String formSelector, List<String> params) {
    if (params.size() % 2 != 0) {
      throw new Exception("There must be an even number of params.");
    }

    Element form= $(formSelector).first();

    Set<String> newParams= Sets.newHashSet();
    for (int i=0; i < params.size(); i+= 2) {
      newParams.add(params.get(i));
    }

    List<String> allParams= Lists.newArrayList(params);
    for (Element field: form.select("input, select, textarea")) {
      String name= field.attr("name");
      if (name == null || newParams.contains(name)) continue;
      String type= field.attr("type").toLowerCase();
      if ("checkbox".equals(type) || "radio".equals(type)) {
        if (field.attr("checked") != null) {
          allParams.add(field.attr("name"));
          allParams.add(field.attr("value"));
        }
      }
      else if (! fieldTypesToIgnore.contains(type)) {
        allParams.add(field.attr("name"));
        allParams.add(field.val());
      }
    }

    String action= form.attr("abs:action");
    String method= form.attr("method").toLowerCase();
    // String encType= form.attr("enctype"); -- TODO

    if ("post".equals(method)) {
      post(action, allParams);
    }
    else {
      get(action, allParams);
    }
  }

($,get和post是我已經躺在那里的方法......你可以很容易地猜到他們做了什么)。

Jsoup在FormElement類中有一個formData方法; 它在簡單的情況下工作,但它並不總是做我需要的,所以我最終也編寫了一些自定義代碼。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM