1. 程式人生 > 實用技巧 >Jsoup獲取網頁內容(並且解決中文亂碼問題)

Jsoup獲取網頁內容(並且解決中文亂碼問題)

1. 根據連線地址獲取網頁內容,解決中文亂碼頁面內容,請求失敗後嘗試3次

private static Document getPageContent(String urlStr) {
        for (int i = 1; i <= 3; i++) {
            try {
                URL url = new URL(urlStr);
                HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                
// 預設就是Get,可以採用post,大小寫都行,因為原始碼裡都toUpperCase了。 connection.setRequestMethod("GET"); // 是否允許快取,預設true。 connection.setUseCaches(Boolean.FALSE); // 是否開啟輸出輸入,如果是post使用true。預設是false // connection.setDoOutput(Boolean.TRUE);
// connection.setDoInput(Boolean.TRUE); // 設定請求頭資訊 connection.addRequestProperty("Connection", "close"); // 設定連線主機超時(單位:毫秒) connection.setConnectTimeout(8000); // 設定從主機讀取資料超時(單位:毫秒) connection.setReadTimeout(8000);
// 設定Cookie // connection.addRequestProperty("Cookie", "你的Cookies"); // 開始請求 int index = urlStr.indexOf("://") + 3; String baseUri = urlStr.substring(0, index) + url.getHost(); Document doc = Jsoup.parse(connection.getInputStream(), "GBK", baseUri); if (doc != null) { return doc; } Thread.sleep(3 * 1000); continue; } catch (Exception e) { e.printStackTrace(); } } return null; }

2. 解析網頁資料,通過多種方式獲取頁面元素

    public static void main(String[] args) {
        String urlStr = "http://test.cn/a.html";// 靜態頁面連結地址
        Document doc = getPageContent(urlStr);
        if (doc != null) {
            // 1. 根據id查詢元素
            Element e1 = doc.getElementById("id");
            // 2. 根據標籤獲取元素
            Elements e2 = doc.getElementsByTag("p");
            // 3. 根據class獲取元素
            Element e3 = doc.getElementsByClass("class_p").first();
            // 4. 根據屬性獲取元素
            Element e4 = doc.getElementsByAttributeValue("href", "http://test.cn").first();
            // 5. 根據查詢器獲取元素(class 為writing的div下的p)
            Elements e5 = doc.select("div.writing>p");
            Elements es = doc.select("div .writing p");
            if (es != null && es.size() > 0) {
                for (Element p : es) {
                    String pStr = p.text().trim();
                    System.out.println(pStr);
                }
            }
        }
    }