hanker

Java - 웹 크롤링 이미지 파일 다운로드(Web Crawling img Download) - jsoup (2) 본문

SPRING

Java - 웹 크롤링 이미지 파일 다운로드(Web Crawling img Download) - jsoup (2)

hanker 2021. 11. 9. 14:20

Image 파일 다운로드 하는 방법

 

이전글 확인

https://hanke-r.tistory.com/161

 

Java - 웹 크롤링(Web Crawling) - jsoup (1)

이번 글은 특정 URL의 이미지 파일을 가져와서 내 웹화면에 띄우는 내용이다. Spring boot 를 이용해서 간단하게 메인페이지에 사진을 가져오려고 한다. Web crawler @Controller @RequiredArgsConstructor public..

hanke-r.tistory.com

 

이전글에 이어서 이번에는 다운로드하는 방법이다.

 

<index.html>

<body>
<button type="button" id="crawlingImgDown">Download</button>
<h2>Web crawler</h2>


<span class="web-crawling"></span>

<script>
	$(function(){
		$.ajax({
			url : "/crawling",
			type : "GET",
			dataType : "json",
			success : function (rs) {

				var html = "";
				html = rs.images;

				$(".web-crawling").append(html);
            }
		});

		$("#crawlingImgDown").click(function(){
			$.ajax({
				url : "/getCrawlingImageDownload",
				type : "POST",
				success : function(rs){
					console.log(rs);
				}
			});
		});


	});
</script>

</body>

- 이전 코드와는 달리 button과 button 클릭시 이벤트 처리를 추가했다.

 

<MainController.java>

    @PostMapping("/getCrawlingImageDownload")
    public String getCrawlingImageDownload(){

        mainService.imgDownload();

        return "jsonView";
    }

 

return "jsonView" 처리는 

https://hanke-r.tistory.com/71

 

Spring boot - jsonView 사용

@Configuration public class WebConfig { @Bean public MappingJackson2JsonView jsonView() { return new MappingJackson2JsonView(); } } @Configuration 설정파일 내에 JsonView() 작성하면 끝!

hanke-r.tistory.com

 

<MainService.java>

public void imgDownload() {

        try{
            Connection conn = Jsoup.connect(CRAWLING_URL);

            Document html = conn.get();

            Elements imageUrlElements = html.getElementsByTag("img");

            for(Element image : imageUrlElements) {
                String imgURL = image.getElementsByAttribute("src").attr("src");

                if (!"".equals(imgURL) && (imgURL.startsWith("http://") || imgURL.startsWith("https://"))) {
                    System.out.println("The address of the picture downloaded: " + imgURL);
                    downImages(DIR, imgURL);

                }
            }

        } catch(Exception e){
            e.printStackTrace();
        }


    }

    private static void downImages(String dir, String imgURL) {
        String[] fileName = imgURL.substring(imgURL.lastIndexOf("/")).split("/");

        File files = new File(dir);

        if(!files.exists()){
            files.mkdir();
        }

        try{
            URL url = new URL(imgURL);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            InputStream is = connection.getInputStream();

            System.out.println("fileName = " + fileName[1]);

            File file = new File(dir + "/" + FILE_NUM + "_"+ fileName[1]);
            FILE_NUM++;
            FileOutputStream out = new FileOutputStream(file);
            int i = 0;

            while((i=is.read()) != -1){
                out.write(i);
            }

            is.close();
            out.close();
        } catch(Exception e){
            e.printStackTrace();
        }
    }

이전글 MainService에 추가해주면 된다.

 

결과