【用Java爬取网页图片——爬虫爬取数据】
生活随笔
收集整理的這篇文章主要介紹了
【用Java爬取网页图片——爬虫爬取数据】
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
用Java爬取網頁圖片——爬蟲爬取數據
1、在創建項目中導入jsoup
2、創建一個保存下載圖片的路徑
3、使用URL讀取網頁路徑,jsoup讀取網頁內容
4、利用屬性標簽獲取圖片連接塊
5、因為該路徑沒有http:頭,用StringBuilder增加
5、完善下載路徑
## 點個關注、不迷路!!!
6、完整代碼
public static void main(String[] args) throws IOException {File dir = new File("./src/main/java/img");if(dir.exists()){System.out.println("該目錄已存在!");}else{dir.mkdirs();System.out.println("該目錄已創建!");}String url ="https://www.nipic.com/topic/show_27202_1.html";Document document = Jsoup.parse(new URL(url), 100000);Element content = document.getElementById("img-list-outer"); // Document document = Jsoup.connect(url).get();System.out.println(content);Elements imgs = content.getElementsByTag("img");//根據標簽屬性System.out.println(imgs);int id=0;for (Element img : imgs) {String imgSrc = img.attr("src");//根據屬性查找StringBuilder builder = new StringBuilder("https:");System.out.println(imgSrc);id++;builder=builder.append(imgSrc);String str2 = builder.toString();System.out.println(str2);URL target = new URL(str2);URLConnection urlConnection = target.openConnection();InputStream is=urlConnection.getInputStream();OutputStream os=new FileOutputStream("./src/main/java/img/"+id+".jpg");int temp=0;while ((temp=is.read())!=-1){os.write(temp);}System.out.println(id+".jpg下載完畢!");os.close();is.close();}}總結
以上是生活随笔為你收集整理的【用Java爬取网页图片——爬虫爬取数据】的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 四种排序:选择,插入,冒泡,快速排序原理
- 下一篇: 【排序算法】快速排序原理及Java实现