2012年12月30日

續談 Groovy 輕鬆擷取網頁內容,使用 jsoup: Java HTML Parser

這個系列教學的上一篇,我們談到 Groovy + NekoHTML 用於網頁內容擷取;接下來我們將繼續分享更多來自 Java 的好用函式庫,這些強大的函式庫只要搭配 Groovy 這個 JVM Scripting Language,就可以變成輕便好用、開發快速的利器。

jsoup 是很先進的 HTML 解析函式庫,它支援 WHATWG HTML5 的標準,可以將 HTML 源碼解析成類似現代瀏覽器使用的 DOM 結構;簡單地說,有了 jsoup 只要使用類似 jQuery Selector 的語法,就可以輕鬆解析網頁內容。

以下是來自 jsoup 官網的一段簡介。

---
jsoup is a Java library for working with real-world HTML. It provides a very convenient API for extracting and manipulating data, using the best of DOM, CSS, and jquery-like methods.
jsoup implements the WHATWG HTML5 specification, and parses HTML to the same DOM as modern browsers do.
  • scrape and parse HTML from a URL, file, or string
  • find and extract data, using DOM traversal or CSS selectors
  • manipulate the HTML elements, attributes, and text
  • clean user-submitted content against a safe white-list, to prevent XSS attacks
  • output tidy HTML
jsoup is designed to deal with all varieties of HTML found in the wild; from pristine and validating, to invalid tag-soup; jsoup will create a sensible parse tree.
---

Groovy 使用 jsoup 超級方便,只要透過一行 @Grab 宣告,就可以自動取得相關函式庫檔案。

    @Grab('org.jsoup:jsoup:1.7.1')

我們擷取的網頁範例仍為 Google News,網址是「https://news.google.com/nwshp?hl=zh-TW&tab=wn」。

透過 Google Chrome 瀏覽器的 Elements 網頁元素觀察,可以發現目標區域「發燒新聞」的 DOM 結構,我們先以 jQuery 的 Selector 觀念來思考怎麼取得標題:

在前端 jQuery JavaScript 程式中,若想取得標題可以透過以下的 Selector 語法,其中 #s_POPULAR 指的是一個 id="s_POPULAR" 的 DOM 標籤節點,而後面的 .titletext 則是指
在 #s_POPULAR 範圍內 class 屬性包含「titletext」的子節點。

    $("#s_POPULAR .titletext")

透過 jsoup 解析一個指定網頁,只需要一行:

    def doc = org.jsoup.Jsoup.connect("https://news.google.com/nwshp?hl=zh-TW&tab=wn").get()

jsoup 有了 jQuery-like selector 的設計,取得我們想要的發燒新聞標題(List),也只需要一行程式碼:

    doc.select("#s_POPULAR .titletext")

上面的 select() 可以取得一個集合,所以透過 .each 語法就能將標題內容印出:

    doc.select("#s_POPULAR .titletext").each {
        node->
        println "title=${node.text()}"
    }

完整程式碼

1 則留言:

  1. s_POPULAR改成s_MOST_POPULAR才能運作喔~~

    回覆刪除

lyhcode by lyhcode
歡迎轉載,請務必註明出處!