我今天开始使用 HtmlUnit,所以当时我有点菜鸟。
我设法去 IMDB 搜索 1996 年的电影“Sleepers”,得到了一堆同名的结果:
Here are the results from that search
我想从列表中选择第一个“Sleepers”,这是正确的,但我不知道如何使用 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");
}
最佳答案
你应该这样做:
HtmlPage htmlPage = new WebClient().getPage("http://imdb.com/blah");
HtmlAnchor anchor = htmlPage.getFirstByXPath("//td[@class='primary_photo']//a")
System.out.println(anchor.getHrefAttribute());
关于java - HtmlUnit 单击具有相同名称的链接引用中的特定链接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18458778/