使用jsoup進行簡單的爬蟲操作爬取圖片



package
com.guanglan.util; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.URL; import java.net.URLConnection; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; import org.jsoup.select.Elements; public class DownLoadPic { public void getDoc() throws IOException{

  File f = new File("E://imgs");

      if(!f.exists()){

         f.mkdirs();

      }
    //以網易為例子

 Document doc = Jsoup.connect("http://www.163.com/").get(); //獲取后綴為png和jpg的圖片的元素集合 Elements pngs = doc.select("img[src~=(?i)\\.(png|jpe?g)]"); //遍歷元素 for(Element e : pngs){ String src=e.attr("src");//獲取img中的src路徑 //獲取后綴名 String imageName = src.substring(src.lastIndexOf("/") + 1,src.length()); //連接url URL url = new URL(src); URLConnection uri=url.openConnection(); //獲取數據流 InputStream is=uri.getInputStream(); //寫入數據流 OutputStream os = new FileOutputStream(new File("E://imgs", imageName)); 

  byte[] buf = new byte[1024];

  int l=0;

  while((l=is.read(buf))!=-1)
{
      os.write(buf, 0, l); 
    }
  }
}
public static void main(String[] args) throws IOException {

    new DownLoadPic().getDoc(); //調用方法

  }
}

  使用之前注意導入jsoup相關jar包


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM