jsoup入门

jsoup是一款Java的HTML解析器,主要用来对HTML解析。官网   中文文档

可直接解析某个URL地址、HTML文本内容。它提供了一套非常省力的API,可通过DOM,CSS以及类似于jQuery的操作方法来取出和操作数据。

jSOUP主要功能

  1. 从一个URL,文件或字符串中解析HTML;
  2. 使用DOM或CSS选择器来查找、取出数据;
  3. 可操作HTML元素、属性、文本

例子:下载一个网站上的图片

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);
            }
        }
    }
}
原文地址:https://www.cnblogs.com/RealWorld/p/8522124.html