jsoup下載圖片

來源:互聯網
上載者:User

標籤:

package test;import java.io.File;import java.io.FileOutputStream;import java.io.IOException;import java.io.InputStream;import java.net.HttpURLConnection;import java.net.URL;import org.jsoup.Jsoup;import org.jsoup.nodes.Document;import org.jsoup.nodes.Element;import org.jsoup.select.Elements;public class download {public static int num = 0;public static void main(String[] args) throws IOException {Document doc = Jsoup.connect("http://guju.com.cn/photos/new").get();Elements elements = doc.select("img[src]");for (Element element : elements) {String imgUrl = element.attr("src");System.out.println(imgUrl);if (!imgUrl.startsWith("http://")) {imgUrl = "http:" + imgUrl;}new Thread(new download().new DownLoadThread(imgUrl)).start();}}public class DownLoadThread implements Runnable {private String imgUrl;public DownLoadThread(String url) {this.imgUrl = url;}@Overridepublic void run() {FileOutputStream out = null;HttpURLConnection conn = null;try {URL url = new URL(imgUrl);conn = (HttpURLConnection) url.openConnection();conn.setRequestMethod("GET");conn.setReadTimeout(5 * 1000);InputStream inputStream = conn.getInputStream();// imgUrl.replaceAll("\\", "_").replaceAll("http:", "");String fileName = "e:\\photo\\"+num++ + ".jpg";out = new FileOutputStream(new File(fileName));byte[] arr = new byte[1024];int len = 0;while ((len = inputStream.read(arr)) != -1) {out.write(arr, 0, len);}System.out.println("=====處理完成====");} catch (Exception e) {e.printStackTrace();} finally {if (out != null) {try {out.close();} catch (IOException e) {e.printStackTrace();}}if (conn != null) {conn.disconnect();}}}}}

jsoup下載圖片

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.