使用jsoup和jquery显示图像文件大小。

时间:2021-11-08 07:52:07

I have a java program to download a webpage, parse the webpage for images and display the order in which they are on the website. What i need is for the program to also display the file sizes of each image.

我有一个java程序下载一个网页,分析网页的图片和显示他们在网站上的顺序。我需要的是程序也显示每个图像的文件大小。

My Code currently:

目前我的代码:

public static void main(String[] args) throws IOException {

    String url = "http://127.0.0.1";   //Url of webpage
    print("Fetching %s...", url);      //output fetching

    Document doc = Jsoup.connect(url).get(); //getting the document

    Elements media = doc.select("[src]"); //parsing the page for images

    print("\nMedia: (%d)", media.size());
    for (Element src : media) {
        print(" * %s: <%s>", src.tagName(), src.attr("abs:src"));

    }

}

Atm this appears as this:

自动柜员机:

<img href="cat.jpg" />
<img href="dog.jpg" />
<img href="horse.jpg" />

Is there a way to have the output to look like this?

是否有办法让输出看起来像这样?

<img href="cat.jpg" /> ---> 54kb
<img href="dog.jpg" /> ---> 74kb
<img href="horse.jpg" /> ---> 102kb

thanks P.s im currently using jsoup however i dont mind using another library if that is what is required

由于P。我现在正在使用jsoup,但是如果需要的话,我不介意使用另一个库。

1 个解决方案

#1


2  

You can use the URL class for this:

您可以使用这个URL类:

for( Element element : media )
{
    final String src = element.absUrl("src");

    if( src.toLowerCase().endsWith(".jpg") ) // only needed if you want to check only jpegs
    {
        final URL url = new URL(src);
        final long size = url.openConnection().getContentLength();

        System.out.println(element + " ---> " + size + " byte");
    }
}

But this will only show the size in Byte!

但这只会显示字节的大小!

For a better readability you can ...

为了更好的可读性,你可以……

  • Convert it to kb, mb etc. by your own
  • 将它转换为kb、mb等等。
  • use FileUtils.byteCountToDisplaySize() of Apache Commons IO: FileUtils.byteCountToDisplaySize(size)
  • 使用FileUtils.byteCountToDisplaySize() Apache Commons IO: FileUtils.byteCountToDisplaySize(大小)

#1


2  

You can use the URL class for this:

您可以使用这个URL类:

for( Element element : media )
{
    final String src = element.absUrl("src");

    if( src.toLowerCase().endsWith(".jpg") ) // only needed if you want to check only jpegs
    {
        final URL url = new URL(src);
        final long size = url.openConnection().getContentLength();

        System.out.println(element + " ---> " + size + " byte");
    }
}

But this will only show the size in Byte!

但这只会显示字节的大小!

For a better readability you can ...

为了更好的可读性,你可以……

  • Convert it to kb, mb etc. by your own
  • 将它转换为kb、mb等等。
  • use FileUtils.byteCountToDisplaySize() of Apache Commons IO: FileUtils.byteCountToDisplaySize(size)
  • 使用FileUtils.byteCountToDisplaySize() Apache Commons IO: FileUtils.byteCountToDisplaySize(大小)