2012-03-05 8 views
2

私はこのコードをしばらく再生していますが、私が間違っていることはわかりません。特定のHTML要素を見つけるためにJTidyから返されたDOMを解析します

URLが取得され、整形式ではないので、JTidyでクリーンアップしてから、特定の非表示の入力フィールド(input type="hidden" name="mytarget" value="313")を見つける必要があるため、name属性の値を知っています。

私は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

JTidyの代わりにJSoupを見ましたか?私は不正な形式の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

私はそれをチェックアウトします、ありがとうございました。 –

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 } 
} 
関連する問題