【发布时间】:2013-08-27 06:48:56
【问题描述】:
我今天开始使用 HtmlUnit,所以我当时有点菜鸟。
我设法去 IMDB 搜索了 1996 年的电影《沉睡者》,我得到了一堆同名的结果:
Here are the results from that search
我想从列表中选择第一个“睡眠者”,这是正确的,但我不知道如何使用 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");
}
【问题讨论】:
-
你能使用这个建议吗?
-
不,因为这不是我想要的,但无论如何谢谢。我终于使用了一些正则表达式来提取一些特定的数据。