gpt4 book ai didi

Java HTML 解析(链接)

转载 作者:行者123 更新时间:2023-12-02 03:59:03 24 4
gpt4 key购买 nike

我正在尝试解析一个网站并从中获取一些内容,但我现在完全迷失了,我正在尝试从 <div class="block block--archive"> 获取所有链接有<a class="block_link" hrek = "/curator/christoffer-rostlund-jonsson/"我想获得这些链接,我搜索了很多有关它的指南,但找不到任何具体的答案。我尝试过一些方法,但我知道它的方式非常愚蠢并且不起作用:

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

最佳答案

这不起作用,因为网站使用 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();

关于Java HTML 解析(链接),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35101798/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com