java 實現百度貼吧“只看樓主”

來源:互聯網
上載者:User

這個功能主要是:先確定文章的地址,然後擷取html代碼, 通過jsoup解析html, 然後把樓主發的提取出來儲存到book.html

除了jsoup的使用, 更多的是要看貼吧文章的大體結構:

1、先解析出樓主的使用者名稱:

差看html代碼可以知道使用者名稱是在class="p_author_name" 的div裡, 樓主當然是第一個,所以:

String lz = doc.getElementsByClass("p_author_name").get(0).html();

2、發現回複的主體是在  class="p_postlist"這個div裡面的, 先把這個提取出來Element e = doc.getElementsByClass("p_postlist").get(0);

3、把每一個回複 class="l_post"取出來, 然後遍曆

Elements es = e.getElementsByClass("l_post");// 把每一個記錄取出來for (Element tmp : es) {// 遍曆if (lz.equals(tmp.getElementsByClass("p_author_name").html())) {//如果是樓主就儲存起來String html = tmp.getElementsByClass("d_content").get(0).html();html = html.replaceAll("<img[\\d\\D]+/>", "[圖片]");sb.append(html);}}

4、判斷文章是否已經到尾頁

每個文章裡面都有兩條分頁, 取出任意一條, 判斷是否包含“下一頁”, 如果沒了, 就是到最後了

5、最後儲存起來

因為我們只提取了div裡面的內容, 所以儲存完有點亂,可以自己先寫個css進行排版後在儲存

完整的代碼:

private void see(String url) {try {int page = 0;StringBuffer sb = new StringBuffer();Document doc = Jsoup.connect(url).get();String lz = doc.getElementsByClass("p_author_name").get(0).html();// 擷取第一個使用者的使用者名稱,即樓主Elements posts = null;do {Element e = doc.getElementsByClass("p_postlist").get(0);// 擷取內容divElements es = e.getElementsByClass("l_post");// 把每一個記錄取出來for (Element tmp : es) {// 遍曆if (lz.equals(tmp.getElementsByClass("p_author_name").html())) {String html = tmp.getElementsByClass("d_content").get(0).html();html = html.replaceAll("<img[\\d\\D]+/>", "[圖片]");sb.append(html);}}// 擷取分頁, 一共有2個posts = doc.getElementsByClass("l_thread_info");page++;doc = Jsoup.connect(url + page).get();} while (posts.html().contains("下一頁"));FileOutputStream fos = new FileOutputStream(new File("d:/book.html"));fos.write(sb.toString().getBytes());fos.flush();fos.close();} catch (IOException e) {e.printStackTrace();}}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.