【问题标题】:Jsoup: Find all images on specified page and also on subpages or inside javascript?Jsoup:查找指定页面以及子页面或javascript内部的所有图像?
【发布时间】:2015-05-26 21:44:37
【问题描述】:

当我尝试在我的 Android 应用程序中的 this 等页面上使用 jsoup example 时,找不到任何图像。是因为内容是通过javascript加载的吗?

现在我的代码如下所示:

Document doc = Jsoup.connect(url).get();
Elements media = doc.select("[src]");

print("\nMedia: (%d)", media.size());
List<Link> tmpLinks = new ArrayList<>();
int i = 0;
for (Element src : media) {
    if (src.tagName().equals("img")) {
        if (!src.attr("abs:src").contains(".png") && !src.attr("abs:src").contains(".gif")) {
            String widthString = src.attr("width");
            int width;
            if (!widthString.isEmpty()) {
                width = Integer.parseInt(src.attr("width"));
            }
            else width = 0;
            String heightString = src.attr("height");
            int height;
            if (!heightString.isEmpty()) {
                height = Integer.parseInt(src.attr("height"));
            }
            else height = 0;

            if (width == 0 || width >= minAllowedWidth) {
                if (!src.attr("abs:src").isEmpty()) {
                    tmpLinks.add(new Link(i, src.attr("abs:src"), width, height));
                }
            }
            i++;
            print(" * %s: <%s> %sx%s (%s)",
                    src.tagName(), src.attr("abs:src"), src.attr("width"), src.attr("height"),
                    trim(src.attr("alt"), 20));
        }
    }
}

List<Link> noDuplicates = new ArrayList<>();
Set<String> titles = new HashSet<>();
for (Link link : tmpLinks ) {
    if (titles.add(link.getUrl())) {
        noDuplicates.add(link);
    }
}

List<Link> finalLinks = new ArrayList<>();
for (Link link : noDuplicates) {
    URL testUrl = new URL(link.getUrl());
    URLConnection urlConnection = testUrl.openConnection();
    urlConnection.connect();
    int file_size = urlConnection.getContentLength();
    System.out.println("Fetching size: " + link.getUrl() + " " + file_size);
    if (file_size >= minAllowedFileSize) {
        link.setSize(file_size);
        finalLinks.add(link);
    }
}
Collections.sort(finalLinks, new LinkSizeComparator());

第二个问题是,我可以用 this 之类的网站上的 jsoup 子页面(或图片链接)进行分析吗?

【问题讨论】:

    标签: java android image jsoup


    【解决方案1】:

    我尝试使用 Jsoup 抓取该网站,但没有得到任何图像,因此显然它不适用于动态网站。

    您可以尝试用户在此线程中的建议 Getting Jsoup to support dynamically generated html by JavaScript

    【讨论】:

    • 谢谢 Eric,但我忘了告诉你,我在 Android 应用程序中使用 jsoup,所以无法使用链接的 javascript 库。我也尝试从 webview 获取 html 作为字符串,但没有成功。
    • 我一直在想一些事情,但我想不出什么太“简单”的东西。我想说:创建一个使用 HtmlUnit(或另一个库,如果有的话)的 web 服务,然后你从 android 使用该服务,你忘记了 Jsoup。我想不出别的了:/。
    • 埃里克,你是对的。我也有同样的想法。但对我来说,现在在服务器端使用 java 应用程序很昂贵,所以可能在将来。但感谢您的回复和提示!
    猜你喜欢
    • 2010-11-02
    • 1970-01-01
    • 2014-07-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-08
    • 2011-05-16
    • 2011-02-01
    相关资源
    最近更新 更多