如何用Jsoup填写表格?

时间:2015-07-02 17:22:32

标签: java web-scraping jsoup

我正在尝试浏览加州网站http://kepler.sos.ca.gov/的说明页面。但无法前往。

然后,我有一个html表单,我提交请求,     我无法在此处添加表单,但只需POSThttp://kepler.sos.ca.gov/请求所需的参数

我可以从我来到这里的上一页获得__EVENTTARGET__EVENTARGUMENT

我做错了什么?

代码:

String url = "kepler.sos.ca.gov/";
Connection.Response resp = Jsoup.connect(url)
                                .timeout(30000)
                                .method(Connection.Method.GET) 
                                .execute();
Document responseDocument = resp.parse();
Map<String, String> loginCookies = resp.cookies();
   eventValidation=responseDocument.select("input[name=__EVENTVALIDATION]").first();
viewState = responseDocument.select("input[name=__VIEWSTATE]").first();

2 个答案:

答案 0 :(得分:11)

您想使用FormElement。这是Jsoup的一个有用功能。它能够找到在表单中声明的​​字段并为您发布它们。在发布表单之前,您可以使用Jsoup API设置字段的值。

  

<强>诺塔:

     

在下面的示例代码中,您始终会看到对Element#select方法的调用,然后调用Elements#first方法。

     

例如:   responseDocument.select("form#aspnetForm").first()

     

Jsoup 1.11.1引入了更有效的替代方案:Element#selectFirst。您可以将其用作原始替代品的直接替代品。

     

例如:
  responseDocument.select("form#aspnetForm").first()
  可以替换为   responseDocument.selectFirst("form#aspnetForm")

示例代码

// * Connect to website
String url = "http://kepler.sos.ca.gov/";
Connection.Response resp = Jsoup.connect(url) //
                                .timeout(30000) //
                                .method(Connection.Method.GET) //
                                .execute();

// * Find the form
Document responseDocument = resp.parse();
Element potentialForm = responseDocument.select("form#aspnetForm").first();
checkElement("form element", potentialForm);
FormElement form = (FormElement) potentialForm;

// * Fill in the form and submit it
// ** Search Type
Element radioButtonListSearchType = form.select("[name$=RadioButtonList_SearchType]").first();
checkElement("search type radio button list", radioButtonListSearchType);
radioButtonListSearchType.attr("checked", "checked");

// ** Name search
Element textBoxNameSearch = form.select("[name$=TextBox_NameSearch]").first();
checkElement("name search text box", textBoxNameSearch);
textBoxNameSearch.val("cali");

// ** Submit the form
Document searchResults = form.submit().cookies(resp.cookies()).post();

// * Extract results (entity numbers in this sample code)
for (Element entityNumber : searchResults.select("table[id$=SearchResults_Corp] > tbody > tr > td:first-of-type:not(td[colspan=5])")) {
    System.out.println(entityNumber.text());
}

public static void checkElement(String name, Element elem) {
    if (elem == null) {
        throw new RuntimeException("Unable to find " + name);
    }
}

输出(撰写本文时)

C3036475
C3027305
C3236514
C3027304
C3034012
C3035110
C3028330
C3035378
C3124793
C3734637

另见:

在此示例中,我们将使用GitHub类登录FormElement网站。

// # Constants used in this example
final String USER_AGENT = "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.103 Safari/537.36"; 
final String LOGIN_FORM_URL = "https://github.com/login";
final String USERNAME = "yourUsername";  
final String PASSWORD = "yourPassword";  

// # Go to login page
Connection.Response loginFormResponse = Jsoup.connect(LOGIN_FORM_URL)
                                             .method(Connection.Method.GET)
                                             .userAgent(USER_AGENT)
                                             .execute();  

// # Fill the login form
// ## Find the form first...
FormElement loginForm = (FormElement)loginFormResponse.parse()
                                         .select("div#login > form").first();
checkElement("Login Form", loginForm);

// ## ... then "type" the username ...
Element loginField = loginForm.select("#login_field").first();
checkElement("Login Field", loginField);
loginField.val(USERNAME);

// ## ... and "type" the password
Element passwordField = loginForm.select("#password").first();
checkElement("Password Field", passwordField);
passwordField.val(PASSWORD);        


// # Now send the form for login
Connection.Response loginActionResponse = loginForm.submit()
         .cookies(loginFormResponse.cookies())
         .userAgent(USER_AGENT)  
         .execute();

System.out.println(loginActionResponse.parse().html());

public static void checkElement(String name, Element elem) {
    if (elem == null) {
        throw new RuntimeException("Unable to find " + name);
    }
}

所有表单数据都由FormElement类为我们处理(甚至是表单方法检测)。调用Connection方法时会生成现成的FormElement#submit。我们所要做的就是用附加标题(cookies,用户代理等)完成这个连接并执行它。

答案 1 :(得分:0)

这与上面在接受的答案中发布的代码完全相同,只是它反映了加利福尼亚州在发布原始答案后对其网站所做的更改。因此,在撰写本文时,此代码有效。我已经更新了原始评论,确定了所有更改。

// * Connect to website (Orignal url: http://kepler.sos.ca.gov/)
String url = "https://businesssearch.sos.ca.gov/";
Connection.Response resp = Jsoup.connect(url) //
                                .timeout(30000) //
                                .method(Connection.Method.GET) //
                                .execute();

// * Find the form (Original jsoup selector: from#aspnetForm)
Document responseDocument = resp.parse();
Element potentialForm = responseDocument.select("form#formSearch").first();
checkElement("form element", potentialForm);
FormElement form = (FormElement) potentialForm;

// * Fill in the form and submit it
// ** Search Type (Original jsoup selector: name$=RadioButtonList_SearchType)
Element radioButtonListSearchType = form.select("name$=SearchType]").first();
checkElement("search type radio button list", radioButtonListSearchType);
radioButtonListSearchType.attr("checked", "checked");

// ** Name search (Original jsoup selector: name$=TextBox_NameSearch)
Element textBoxNameSearch = form.select("[name$=SearchCriteria]").first();
checkElement("name search text box", textBoxNameSearch);
textBoxNameSearch.val("cali");

// ** Submit the form
Document searchResults = form.submit().cookies(resp.cookies()).post();

// * Extract results (entity numbers in this sample code, orignal jsoup selector: id$=SearchResults_Corp)
for (Element entityNumber : searchResults.select("table[id$=enitityTable] > tbody > tr > td:first-of-type:not(td[colspan=5])")) {
    System.out.println(entityNumber.text());
}