2016-01-30 66 views
0

我想解析一个网站,并从中获取一些内容,但我现在完全失去了,我试图从<div class="block block--archive">得到所有的链接有<a class="block_link" hrek = "/curator/christoffer-rostlund-jonsson/"我想要得到这些链接,我已经搜索了很多关于它的指南,但找不到任何具体的答案。我已经试过的东西,但我真的很愚蠢的方式行不通知道它:Java的HTML解析(链接)

public static void main(String[]args) throws IOException { 
     Document doc = Jsoup.connect("http://curatorsofsweden.com/archive/").get(); 
     Elements articles = doc.select("body"); 
     Elements element2= articles.select("div"); 
     Elements element3 = element2.select("article"); 
     Elements element4 = element3.select("div"); 
     System.out.println(element4.toString()); 
     } 

这里是我想从得到的链接网站的结构: enter image description here

回答

2

此次荣获”因为该网站使用JavaScript来加载你想要的内容。 Jsoup无法执行JavaScript,它只是一个HTML解析器。要验证,您可以从JSOUP获取HTML并将其保存为文件:

Document doc = Jsoup.connect("http://curatorsofsweden.com/archive/").get(); 
Files.write(Paths.get("./website.html"), doc.html().getBytes()); 

您正在查找的内容不存在。您可以尝试Selenium Webdriver。该库使用真正的浏览器并执行JavaScript。这个例子打印您要找的链接:

WebDriver driver = new FirefoxDriver(); 
driver.get("http://curatorsofsweden.com/archive/"); 

By linkSelector = By.cssSelector("div[class='block block--archive'] a"); 

WebDriverWait wait = new WebDriverWait(driver, 2); 
wait.until(ExpectedConditions.presenceOfElementLocated(linkSelector)); 

List<WebElement> linkElements = driver.findElements(linkSelector); 
for (WebElement linkElement : linkElements) { 
    String link = linkElement.getAttribute("href"); 
    System.out.println("LINK " + link); 
} 
driver.quit(); 
+0

我现在想的话,会在5分钟内回答,谢谢:) – Tano

+0

此行让我无法解析的方法:// wait.until(ExpectedConditions。 presenceOfElementLocated(linkSelector)); – Tano

+1

不客气。这是一个完整的导入要点:https://gist.github.com/squallified/bbd39ee12c10b592c840 – Cyril