2012-03-05 30 views
2

我一直在玩這段代碼一段時間,並且我不確定我做錯了什麼。我得到一個url,用JTidy清理它,因爲它不是格式良好的,那麼我需要找到一個特定的隱藏輸入字段(input type="hidden" name="mytarget" value="313"),所以我知道name屬性中的值。解析從JTidy返回的DOM來查找特定的HTML元素

我打印出整個html頁面時,它會清理它,只是爲了讓我可以比較我在找什麼與文檔中的內容。

我的問題是試圖確定最好的方式來找到這個,關於我在哪裏有System.out << it

def http = new HTTPBuilder(url) 
    http.request(GET,TEXT) { req -> 
     response.success = { resp, reader -> 
      assert resp.status == 200 
      def tidy = new Tidy() 
      def node = tidy.parse(reader, System.out) 
      def doc = tidy.parseDOM(reader, null).documentElement 
      def nodes = node.last.last 
      nodes.each{System.out << it} 
     } 
     response.failure = { resp -> println resp.statusLine } 
    } 

回答

4

您是否嘗試過看看JSoup而不是JTidy?我不確定它處理格式不正確的HTML內容的好處,但我已經成功地使用它來解析HTML頁面並使用JQuery樣式選擇器查找我需要的元素。這比手動遍歷DOM容易得多,除非你知道DOM的確切佈局。

@Grab(group='org.codehaus.groovy.modules.http-builder', module='http-builder', version='0.5.2') 
@Grab(group='org.jsoup', module='jsoup', version='1.6.1') 

import groovyx.net.http.HTTPBuilder 
import static groovyx.net.http.Method.GET 
import static groovyx.net.http.ContentType.TEXT 
import org.jsoup.Jsoup 

def url = 'http://stackoverflow.com/questions/9572891/parsing-dom-returned-from-jtidy-to-find-a-particular-html-element' 

new HTTPBuilder(url).request(GET, TEXT) { req -> 
    response.success = { resp, reader -> 
     assert resp.status == 200 
     def doc = Jsoup.parse(reader.text) 
     def els = doc.select('input[type=hidden]') 
     els.each { 
      println it.attr('name') + '=' + it.attr('value') 
     } 
    } 
    response.failure = { resp -> println resp.statusLine } 
} 
+0

我會檢查出來,謝謝。 – 2012-03-05 23:57:51

2

您還可以使用nekohtml:

@Grab(group='org.codehaus.groovy.modules.http-builder', module='http-builder', version='0.5.2') 
@Grab(group='net.sourceforge.nekohtml', module='nekohtml', version='1.9.15') 

import groovyx.net.http.HTTPBuilder 
import static groovyx.net.http.Method.GET 
import static groovyx.net.http.ContentType.TEXT 
import org.cyberneko.html.parsers.SAXParser 

def url = 'http://stackoverflow.com/questions/9572891/parsing-dom-returned-from-jtidy-to-find-a-particular-html-element' 

new HTTPBuilder(url).request(GET, TEXT) { req -> 
    response.success = { resp, reader -> 
     assert resp.status == 200 
     def doc = new XmlSlurper(new SAXParser()).parseText(reader.text) 
     def els = doc.depthFirst().grep { it.name() == 'INPUT' && [email protected]?.toString() == 'hidden' } 
     els.each { 
      println "${[email protected]}=${[email protected]}" 
     } 
    } 
    response.failure = { resp -> println resp.statusLine } 
}