使用Java保存网页中的所有图像

时间:2017-10-16 12:29:34

标签: java image

我正在编写一个小项目,我必须从不同的网页下载所有图像。 我尝试了一个我在解决方案中找到的代码,它仍然无法为我工作 代码:

import java.io.BufferedReader;
import java.io.InputStreamReader;
import javax.swing.text.html.HTML;
import javax.swing.text.html.HTMLEditorKit;
import javax.swing.text.html.parser.ParserDelegator;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import javax.imageio.ImageIO;
import javax.swing.text.AttributeSet;
import javax.swing.text.html.HTMLDocument;

public class ExtractAllImages {

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

        String webUrl = "https://www.pexels.com/search/HD%20wallpaper/";
        URL url = new URL(webUrl);
        URLConnection connection = url.openConnection();
        InputStream is = connection.getInputStream();
        InputStreamReader isr = new InputStreamReader(is);
        BufferedReader br = new BufferedReader(isr);

        HTMLEditorKit htmlKit = new HTMLEditorKit();
        HTMLDocument htmlDoc = (HTMLDocument) htmlKit.createDefaultDocument();
        htmlKit.read(br, htmlDoc, 0);

        for (HTMLDocument.Iterator iterator = htmlDoc.getIterator(HTML.Tag.A); iterator.isValid(); iterator.next()) {
            AttributeSet attributes = iterator.getAttributes();
            String imgSrc = (String) attributes.getAttribute(HTML.Attribute.HREF);

            System.out.println(imgSrc);
            if (imgSrc != null && (imgSrc.toLowerCase().endsWith(".jpg") || (imgSrc.endsWith(".png")) || (imgSrc.endsWith(".jpeg")) || (imgSrc.endsWith(".bmp")) || (imgSrc.endsWith(".ico")))) {
                try {
                    downloadImage(webUrl, imgSrc);
                } catch (IOException ex) {
                    System.out.println(ex.getMessage());
                }
            }
        }
    }
    private static void downloadImage(String url, String imgSrc) throws IOException {
        BufferedImage image = null;
        try {
            if (!(imgSrc.startsWith("http"))) {
                url = url + imgSrc;
            } else {
                url = imgSrc;
            }
            imgSrc = imgSrc.substring(imgSrc.lastIndexOf("/") + 1);
            String imageFormat = null;
            imageFormat = imgSrc.substring(imgSrc.lastIndexOf(".") + 1);
            String imgPath = null;
            imgPath = "C:/Check/" + imgSrc + "";
            URL imageUrl = new URL(url);
            image = ImageIO.read(imageUrl);
            if (image != null) {
                File file = new File(imgPath);
                ImageIO.write(image, imageFormat, file);
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }

    }
}

我得到的错误:

  

线程“main”中的异常java.io.IOException:服务器返回HTTP   响应代码:403为URL:   return a promise from webpack.config.js at   sun.net.www.protocol.http.HttpURLConnection.getInputStream0(未知   来源)at   sun.net.www.protocol.http.HttpURLConnection.getInputStream(未知   来源)at   sun.net.www.protocol.https.HttpsURLConnectionImpl.getInputStream(未知   Source)在ExtractAllImages.main(ExtractAllImages.java:23)

任何帮助都将受到高度赞赏。感谢。

修改
我尝试过其他网页,有时根本没有任何错误,仍然没有图像保存到我的路径。 在某些网页上,我收到了这个错误:

  

线程“main”中的异常javax.swing.text.ChangedCharSetException     在javax.swing.text.html.parser.DocumentParser.handleEmptyTag(未知   来源)在javax.swing.text.html.parser.Parser.startTag(未知   来源)在javax.swing.text.html.parser.Parser.parseTag(未知   来源)在javax.swing.text.html.parser.Parser.parseContent(未知   来自)javax.swing.text.html.parser.Parser.parse(未知来源)     在javax.swing.text.html.parser.DocumentParser.parse(未知来源)     在javax.swing.text.html.parser.ParserDelegator.parse(未知来源)     在javax.swing.text.html.HTMLEditorKit.read(未知来源)at   ExtractAllImages.main(ExtractAllImages.java:29)

编写此代码的其他任何方式?

1 个答案:

答案 0 :(得分:0)

HTTP error 403表示服务器拒绝来自客户端的请求。通常,您可以通过更改user-agent值来将您的客户介绍为其他人来绕过此类检查。

要更改用户代理,您可以调用此代码(例如,在代码的第一行):

System.setProperty("http.agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/61.0.3163.100 Safari/537.36");

此更改后,您的应用程序将能够毫无问题地连接到提到的页面(或类似页面),因为它将作为Chrome浏览器引入。

无论如何,您的申请中几乎没有其他问题。实现应用程序时请记住:

  1. 您正在使用imgSrc.toLowerCase()。endsWith(“。jpg”)。在现实世界中,许多图像链接不以.jpg结尾,而是以参数形式结束,例如:https://images.pexels.com/photos/33109/fall-autumn-red-season.jpg?h=350&auto=compress&cs=tinysrgb。您应该至少考虑使用imgSrc.toLowerCase().contains(".jpg")方法。
  2. 使用img标记将图片添加到网页中。在这种情况下,您应该搜索img代码并获取src property,其中设置了图片路径。
  3. 如果是www.pexels.com,当您点击壁纸时,您将被重定向到第二页,您可以在其中下载壁纸。您的应用程序正在尝试从主页面下载图像。您应首先打开第二页并从那里下载所需的图像。