jsoup是一款Java的HTML解析器,主要用来对HTML解析。官网 中文文档html
可直接解析某个URL地址、HTML文本内容。它提供了一套很是省力的API,可经过DOM,CSS以及相似于jQuery的操做方法来取出和操做数据。java
例子:下载一个网站上的图片node
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; /** * 利用Java实现搜索引擎爬虫技术 * * @version v1.0 */ public class Test { /** * 根据图片的url地址,下载图片到服务器 * * @param filepath * 文件存放路径 * @param imageUrl * 图片url * @return void */ public static void downImage(String filepath, String imageUrl) { String fileName = imageUrl.substring(imageUrl.lastIndexOf("/")); // 建立一个文件目录 try { File files = new File(filepath); if (!files.exists()) { files.mkdirs(); } // 获取下载连接 URL url = new URL(imageUrl); // 链接网络地址 HttpURLConnection connection = (HttpURLConnection) url.openConnection(); // 获取链接的输出流 InputStream is = connection.getInputStream(); // 建立文件 File file = new File(filepath + fileName); // 创建输入流,写入文件 FileOutputStream fos = new FileOutputStream(file); int temp = 0; while ((temp = is.read()) != -1) { fos.write(temp); } is.close(); fos.close(); } catch (Exception e) { e.printStackTrace(); } } // Java入口 public static void main(String[] args) { // 解析源代码 Document document = null; try { document = Jsoup.connect("http://news.163.com/18/0306/13/DC7GIBMB000187VE.html").get(); } catch (IOException e) { e.printStackTrace(); } // 获取全部图片的地址<img src="" alt="" width="" height=""/> Elements elements = document.getElementsByTag("img"); for (Element element : elements) { String imgSrc = element.attr("src"); System.out.println("网络图片的地址:" + imgSrc); if (!"".equals(imgSrc) && imgSrc.startsWith("http://")) { System.out.println("正在批量下载图片..." + imgSrc); downImage("C:\\Users\\shay_deng\\Desktop\\下载图片测试", imgSrc); } } } }