Jsoup爬取html數據

1.Jsoup是什麼?

jsoup 是一款Java 的HTML解析器,可直接解析某個URL地址、HTML文本內容。它提供了一套非常省力的API,可通過DOM,CSS以及類似於jQuery的操作方法來取出和操作數據。

2.Jsoup的主要功能?

從一個URL,文件或字符串中解析HTML;使用DOM或CSS選擇器來查找、取出數據;可操作HTML元素、屬性、文本。

3.Jsoup怎麼用?

可以參考:https://www.open-open.com/jsoup/

4.Jsoup案例?

當然在使用Jsoup的時候首先肯定要下載它的jar包。http://jsoup.org/packages/jsoup-1.8.1.jar

a.利用Jsoup下載某個網址的所有圖片。

package com.zhouyajuan;

import org.jsoup.Connection;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.io.*;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;

public class SearchData {
    /**
     * 下載圖片到指定目錄
     *
     * @param filePath 文件路徑
     * @param imgUrl   圖片URL
     */
    public static void downImages(String filePath, String imgUrl) {
        // 若指定文件夾沒有,則先創建
        File dir = new File(filePath);
        if (!dir.exists()) {
            dir.mkdirs();
        }
        // 截取圖片文件名
        String fileName = imgUrl.substring(imgUrl.lastIndexOf('/') + 1, imgUrl.length());

        try {
            // 文件名裏面可能有中文或者空格,所以這裏要進行處理。但空格又會被URLEncoder轉義爲加號
            String urlTail = URLEncoder.encode(fileName, "UTF-8");
            // 因此要將加號轉化爲UTF-8格式的%20
            imgUrl = imgUrl.substring(0, imgUrl.lastIndexOf('/') + 1) + urlTail.replaceAll("\\+", "\\%20");

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        // 寫出的路徑
        File file = new File(filePath + File.separator + fileName);

        try {
            // 獲取圖片URL
            URL url = new URL(imgUrl);
            // 獲得連接
            URLConnection connection = url.openConnection();
            // 設置10秒的相應時間
            connection.setConnectTimeout(10 * 1000);
            // 獲得輸入流
            InputStream in = connection.getInputStream();
            // 獲得輸出流
            BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(file));
            // 構建緩衝區
            byte[] buf = new byte[1024];
            int size;
            // 寫入到文件
            while (-1 != (size = in.read(buf))) {
                out.write(buf, 0, size);
            }
            out.close();
            in.close();
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    public static void main(String[] args) {
        // 利用Jsoup獲得連接
        Connection connect = Jsoup.connect("http://www.qq.com");
        try {
            // 得到Document對象
            Document document = connect.get();
            // 查找所有img標籤
            Elements imgs = document.getElementsByTag("img");
            System.out.println("共檢測到下列圖片URL:");
            System.out.println("開始下載");
            // 遍歷img標籤並獲得src的屬性
            for (Element element : imgs) {
                //獲取每個img標籤URL "abs:"表示絕對路徑
                String imgSrc = element.attr("abs:src");
                // 打印URL
                System.out.println(imgSrc);
                //下載圖片到本地
                SearchData.downImages("E:/program/tooljsoup/img", imgSrc);
            }
            System.out.println("下載完成");





        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

b.利用Jsoup獲取某個網址的所有鏈接。

package com.zhouyajuan;
import org.jsoup.Jsoup;
import org.jsoup.helper.Validate;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.io.IOException;

/**
 * Example program to list links from a URL.
 */
public class ListLinks {
    public static void main(String[] args) throws IOException {
        Document doc = Jsoup.connect("http://www.qq.com").get();
        Elements links = doc.select("a[href]");
        Elements media = doc.select("[src]");
        Elements imports = doc.select("link[href]");

        print("\nMedia: (%d)", media.size());
        for (Element src : media) {
            if (src.tagName().equals("img"))
                print(" * %s: <%s> %sx%s (%s)",
                        src.tagName(), src.attr("abs:src"), src.attr("width"), src.attr("height"),
                        trim(src.attr("alt"), 20));
            else
                print(" * %s: <%s>", src.tagName(), src.attr("abs:src"));
        }

        print("\nImports: (%d)", imports.size());
        for (Element link : imports) {
            print(" * %s <%s> (%s)", link.tagName(),link.attr("abs:href"), link.attr("rel"));
        }

        print("\nLinks: (%d)", links.size());
        for (Element link : links) {
            print(" * a: <%s>  (%s)", link.attr("abs:href"), trim(link.text(), 35));
        }
    }

    private static void print(String msg, Object... args) {
        System.out.println(String.format(msg, args));
    }

    private static String trim(String s, int width) {
        if (s.length() > width)
            return s.substring(0, width-1) + ".";
        else
            return s;
    }
}

c.利用Jsoup解析某個網址的具體顯示內容

 public static List<MyIp> getIp(String url) {
        List<MyIp> ipList = null;
        try {
            //1.向ip代理地址發起get請求,拿到代理的ip
            Document doc = Jsoup.connect(url)
                    .userAgent("Mozilla")
                    .cookie("auth", "token")
                    .timeout(3000)
                    .get();

            //2,將得到的ip地址解析除字符串
            String ipStr = doc.body().text().trim().toString();

            //3.用正則表達式去切割所有的ip
            String[] ips = ipStr.split("\\s+");

            //4.循環遍歷得到的ip字符串,封裝成MyIp的bean
            ipList = new ArrayList<MyIp>();
            for(final String ip : ips) {
                MyIp myIp = new MyIp();
                String[] temp = ip.split(":");
                myIp.setAddress(temp[0].trim());
                myIp.setPort(temp[1].trim());
                ipList.add(myIp);
            }
        } catch (IOException e) {
            System.out.println("加載文檔出錯");
        }
        return ipList;
    }

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章