Use jsoup for simple crawler operations to crawl images and jsoup Crawlers

Source: Internet
Author: User

Use jsoup for simple crawler operations to crawl images and jsoup Crawlers


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 ();

}
// Take Netease as an Example

Document doc = Jsoup. connect ("http://www.163.com /"). get (); // obtain the element set of images suffixed with png and jpg Elements pngs = doc. select ("img [src ~ = (? I) \. (png | jpe? G)] "); // traversal Element for (Element e: pngs) {String src = e. attr ("src"); // obtain the src path in img // obtain the suffix String imageName = src. substring (src. lastIndexOf ("/") + 1, src. length (); // connection url URL url = new URL (src); URLConnection uri = url. openConnection (); // obtain the data stream InputStream is = uri. getInputStream (); // write data stream OutputStream OS = new FileOutputStream (new File ("E: // imgs", ImageName ));

Byte [] buf = new byte [1, 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 (); // CALL THE METHOD

}
}

Before using jsoup, import relevant jar packages.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.