3

私はしばらくこのコードをいじっていましたが、何が間違っているのかわかりません。

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

2 に答える 2

5

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 }
}
于 2012-03-05T23:39:55.917 に答える
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' && it.@type?.toString() == 'hidden' }
        els.each {
            println "${it.@name}=${it.@value}"
        }
    }
    response.failure = { resp -> println resp.statusLine }
}
于 2012-03-06T10:06:33.157 に答える