TagSoupを使用して整形式の構造体をXMLSlurperに渡すHTMLパーサーを作成しています。
一般化されたコードは次のとおりです。
def htmlText = """
<html>
<body>
<div id="divId" class="divclass">
<h2>Heading 2</h2>
<ol>
<li><h3><a class="box" href="#href1">href1 link text</a> <span>extra stuff</span></h3><address>Here is the address<span>Telephone number: <strong>telephone</strong></span></address></li>
<li><h3><a class="box" href="#href2">href2 link text</a> <span>extra stuff</span></h3><address>Here is another address<span>Another telephone: <strong>0845 1111111</strong></span></address></li>
</ol>
</div>
</body>
</html>
"""
def html = new XmlSlurper(new org.ccil.cowan.tagsoup.Parser()).parseText( htmlText );
html.'**'.grep { it.@class == 'divclass' }.ol.li.each { linkItem ->
def link = linkItem.h3.a.@href
def address = linkItem.address.text()
println "$link: $address\n"
}
それぞれが、対応するhrefとアドレスの詳細を取得できるように、それぞれの「li」を順番に選択できるようになることを期待しています。代わりに、次の出力を取得しています。
#href1#href2: Here is the addressTelephone number: telephoneHere is another addressAnother telephone: 0845 1111111
Webでさまざまな例を確認しましたが、これらはXMLを扱っているか、「このファイルからすべてのリンクを取得する」などのワンライナーの例です。it.h3.a.@href式は、親の「li」ノードへの参照を渡していますが、テキスト内のすべてのhrefを収集しているようです。
教えていただけますか:
- 出力が表示される理由
- 各「li」アイテムのhref/addressペアを取得する方法
ありがとう。