Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/351.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
用Java保存网页中的所有图像_Java_Image - Fatal编程技术网

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

用Java保存网页中的所有图像,java,image,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.ParserD

我正在写一个小项目,有一部分我必须从不同的网页下载所有的图片。 我尝试了在解决方案中找到的代码,但它仍然不适用于我。
守则:

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 URL的响应代码:403: 在 sun.net.www.protocol.http.HttpURLConnection.getInputStream0(未知 来源)在 sun.net.www.protocol.http.HttpURLConnection.getInputStream(未知 来源)在 sun.net.www.protocol.https.HttpsURLConnectionImpl.getInputStream(未知 Source)位于extractalImages.main(extractalImages.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(未知源代码) main(extractalImages.java:29)

是否有其他方法编写此代码?

表示服务器拒绝了客户端的请求。通常,您可以通过改变价值,将您的客户介绍为其他人,从而绕过这种检查

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

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

无论如何,应用程序中几乎没有其他问题。在实施应用程序时,请牢记以下几点:

  • 您正在使用imgSrc.toLowerCase().endsWith(“.jpg”)。在现实世界中,许多图像链接不是以.jpg结尾,而是以参数结尾,例如:。你至少应该考虑使用<代码> imgSrc.ToWoReCasee()。包含(“.jpg”)< /Cult>方法。
  • 使用标记将图像添加到网页。在这种情况下,您应该搜索
    img
    标记,并获取设置图像路径的src
    property
  • 如果使用
    www.pexels.com
    ,当您单击墙纸时,您将被重定向到第二页,您可以在那里下载墙纸。您的应用程序正在尝试从主页下载图像。您应该首先打开第二页并从那里下载所需的图像

  • 如果站点不主动阻止此类请求,则该代码有效。。。HTTP 403禁止客户端错误状态响应代码表示服务器理解请求,但拒绝授权。当我在其他网页上尝试时,没有错误,但什么也没有发生。同样,此网站正在阻止您的请求。我不能代表其他网站发言,但你希望发生什么?是
    “C:/Check/
    empty?是的,我尝试了一些网页,代码运行正常,没有错误,但根本没有图像保存。在windows上,文件路径类似于C:\\path\\,不确定是否可以修复任何问题,尽管我很困惑,但我已经像你说的那样在第一行添加了用户代理行。我将imgSrc改为contains而不是endsWith,我尝试了一下,但什么也没发生。我在这段代码中的目标是下载网页现在获得的所有图像。这听起来是因为缺乏知识,不幸的是需求太复杂,很难解释。您需要自己测试和调试代码。当你碰到一个问题时,提出问题,我们会尽力帮助你。我试着回答你最初的问题并给你一些提示。这取决于你做一项研究,提出比“什么都没发生”更具体的问题。
    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");