1

我今天开始使用 HtmlUnit,所以当时我有点菜鸟。

我设法去 IMDB 并搜索了 1996 年的电影“沉睡者”,我得到了一堆同名的结果:

这是该搜索的结果

我想从列表中选择第一个“睡眠者”,这是正确的,但我不知道如何使用 HtmlUnit 获取该信息。我查看了代码并找到了链接,但我不知道如何提取它。

我想我可以使用一些正则表达式,但这会破坏使用 HtmlUnit 的目的。

这是我的代码(它有一些来自 HtmlUnit 的教程和一些代码在这里找到):

public IMdB() {
    try {
        //final WebClient webClient = new WebClient();

        final WebClient webClient = new WebClient(BrowserVersion.INTERNET_EXPLORER_8, "10.255.10.34", 8080);

        //set proxy username and password 
        final DefaultCredentialsProvider credentialsProvider = (DefaultCredentialsProvider) webClient.getCredentialsProvider();
        credentialsProvider.addCredentials("xxxx", "xxxx");

        // Get the first page
        final HtmlPage page1 = webClient.getPage("http://www.imdb.com");

        // 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.getFormByName("navbar-form");
        HtmlForm form = page1.getFirstByXPath("//form[@id='navbar-form']");

        //
        HtmlButton button = form.getFirstByXPath("/html/body//form//button[@id='navbar-submit-button']");            
        HtmlTextInput textField = form.getFirstByXPath("/html/body//form//input[@id='navbar-query']");

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

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

       // form = page2.getElementByName("s");

        //page2 = page2.getFirstByXPath("/html/body//form//div//tr[@href]");

        System.out.println("content: " + page2.asText());

        webClient.closeAllWindows();
    } catch (IOException ex) {
        Logger.getLogger(IMdB.class.getName()).log(Level.SEVERE, null, ex);
    }

    System.out.println("END");
}
4

2 回答 2

1

你应该这样做:

HtmlPage htmlPage = new WebClient().getPage("http://imdb.com/blah");
HtmlAnchor anchor = htmlPage.getFirstByXPath("//td[@class='primary_photo']//a")
System.out.println(anchor.getHrefAttribute());
于 2013-08-27T21:49:26.110 回答
0

我建议你宁愿使用IMDB apithen 做所有这些

IMDb 目前有两个公共 API,虽然没有记录,但非常快速和可靠(通过 AJAX 在他们自己的站点上使用)。

  1. 静态缓存的搜索建议 API:

  2. 更高级的搜索

于 2013-08-27T07:39:43.230 回答