Jsoup(四)-- Jsoup獲取DOM元素屬性值


1.獲取博客園的博客標題以及博客地址,獲取友情鏈接

   

2.代碼實現:

public static void main(String[] args) throws Exception{
        // 創建httpClient實例
        CloseableHttpClient httpClient = HttpClients.createDefault();
        // 創建httpGet實例
        HttpGet httpGet = new HttpGet("http://www.cnblogs.com");
        httpGet.setHeader("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:45.0) Gecko/20100101 Firefox/45.0");
        CloseableHttpResponse response = httpClient.execute(httpGet);
        String content = null;
        if(response != null){
            HttpEntity entity = response.getEntity();   
            content = EntityUtils.toString(entity, "UTF-8");  // 獲取網頁內容
            Document document = Jsoup.parse(content);  // 解析網頁,得到文檔對象
            
            // 1.通過選擇器查找所有博客標題以及鏈接
            Elements ele = document.select("#post_list .post_item .post_item_body h3 a");
            for(Element e : ele){
                System.out.println("博客標題:" + e.text() + "---博客地址:" + e.attr("href"));
            }
            
            // 2.獲取友情鏈接
            Element linkEle = document.select("#friend_link").first();
            System.out.println("友情鏈接純文本:" + linkEle.text());
            System.out.println("友情鏈接HTML:" + linkEle.html());
        }
        if(response != null){
            response.close();
        }
        if(httpClient != null){
            httpClient.close();
        }
    }

3.Jsoup學習地址

  開源博客系統-Jsoup

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM