【问题标题】:Jsoup only fetches few lines of the HTML from start which is not even 25%Jsoup 从一开始只获取几行 HTML,甚至不到 25%
【发布时间】:2020-06-16 03:54:07
【问题描述】:

当我尝试在网站上执行 CTRL+U 时,它也比我从 jsoup 得到的更多。正在使用的站点是 Open SAP -> https://open.sap.com/courses 已尝试超时和 maxbodysize 以及 jsoup.connect。 现在我的代码如下所示:

private static String getHtml(String location) throws IOException {
    URL url = new URL(location);
    URLConnection conn = url.openConnection();
    BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
    String input;
    StringBuilder builder = new StringBuilder();
    while((input = in.readLine()) != null)
    {
         builder.append(input);
    }

    return builder.toString();
}
document = Jsoup.parse(getHtml(URL));

但仍然返回相同的 HTML。通过硒它是可能的,但它有点慢所以任何其他方式来实现这一点? 因为目标是找出课程的链接,然后加载它们以找到他们的课程摘要,使用 selenium 会太慢。

请建议在这里可以做什么。

【问题讨论】:

  • 您不必下载 HTML。 Jsoup 可以为您做到这一点,只需使用:Jsoup.connect(URL).get(); 而不是 Jsoup.parse(getHtml(URL));
  • 感谢您的回复,但我在问题中提到我也尝试过使用 jsoup.connect 但它没有用。

标签: selenium web-scraping jsoup htmlunit


【解决方案1】:

这个页面的页面内容是在你的浏览器内部基于js构建的。您需要一个支持 js 的框架来执行此操作。

使用 HtmlUnit 我得到了这样的页面

String url = "https://open.sap.com/courses";

try (final WebClient webClient = new WebClient(BrowserVersion.FIREFOX_68)) {
    webClient.getOptions().setThrowExceptionOnScriptError(false);

    HtmlPage page = webClient.getPage(url);
    webClient.waitForBackgroundJavaScriptStartingBefore(10_000);

    System.out.println("-------------------------------");
    System.out.println(page.asText());
    System.out.println("-------------------------------");
}

HtmlUnit 具有丰富的 API,可以对页面对象执行您喜欢的所有操作,例如搜索控件/内容、单击控件或从页面的某些部分提取文本。

【讨论】:

  • 我认为您的解决方案也可以。但我使用 selenium 无头模式实现了预期的结果,以抓取我需要的信息。它很慢但有效。您认为上述解决方案会让我更快地获取结果吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-03-30
  • 2023-04-10
  • 2022-11-30
  • 1970-01-01
相关资源
最近更新 更多