与网页自动交互

时间:2011-01-22 14:13:37

标签: java javascript android webforms

我需要从只接受表单作为输入的web page中检索信息。

我通常使用HttpClient来检索信息并解析html,但是这个页面采用Javascript而不是显式url作为参数,并再次打印输入为javascript。

我尝试过HTMLUnit但速度很慢,特别是在Android上。此外,似乎我无法使其正常工作,因为我无法在填写表单后检索html,可能是由于页面是javascrpit(请参阅附带的代码)。

如何在Android中检索此web page的信息?

干杯:D

package com.htmlUnitTest;

import com.gargoylesoftware.htmlunit.WebClient;
import com.gargoylesoftware.htmlunit.html.HtmlForm;
import com.gargoylesoftware.htmlunit.html.HtmlPage;
import com.gargoylesoftware.htmlunit.html.HtmlSubmitInput;
import com.gargoylesoftware.htmlunit.html.HtmlTextInput;

public class HtmlUnitTest {

    /**
     * @param args
     */
    public static void main(String[] args) {

        try {

            submittingForm();


        } catch (Exception e) {

            System.out.println("Something bad happened");

            e.printStackTrace();
        }



    }



    static public void submittingForm() throws Exception {
        final WebClient webClient = new WebClient();

        // Get the first page
        final HtmlPage page1 = webClient.getPage(
                  "http://mobile.viaggiatreno.it/viaggiatreno/mobile/stazione?lang=IT");

        System.out.println(page1.getForms());

        // Get the form that we are dealing with and within that form, 
        // find the submit button and the field that we want to change.
        final HtmlForm form = page1.getForms().get(0);

        final HtmlSubmitInput button = form.getInputByValue(" Cerca ");
        final HtmlTextInput textField = form.getInputByName("stazione");

        // Change the value of the text field
        textField.setValueAttribute("Milano Centrale");

        // Now submit the form by clicking the button and get back the second page.
        final HtmlPage page2 = button.click();

        System.out.println(page2.getAnchors());

        webClient.closeAllWindows();
    }


}

1 个答案:

答案 0 :(得分:1)

您需要发送到/ viaggiatreno / mobile / stazione,解析答案,然后再次发布,如果您想要向下钻取。有关此处发布的更多信息:google.com/search?q=webClient+post