And*_*use 8 html groovy parsing xmlslurper
我正在编写一个HTML解析器,它使用TagSoup将格式良好的结构传递给XMLSlurper.
这是通用代码:
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"
}
Run Code Online (Sandbox Code Playgroud)
我希望每个人都允许我依次选择每个'li',这样我就可以检索相应的href和地址细节.相反,我得到这个输出:
#href1#href2: Here is the addressTelephone number: telephoneHere is another addressAnother telephone: 0845 1111111
Run Code Online (Sandbox Code Playgroud)
我已经在网上检查过各种各样的例子,这些例子要么处理XML,要么就像"从这个文件中检索所有链接"这样的单行示例.似乎it.h3.a. @ href表达式正在收集文本中的所有href,即使我传递了对父"li"节点的引用.
你能让我知道吗:
谢谢.
mbr*_*ort 11
用find替换grep:
html.'**'.find { it.@class == 'divclass' }.ol.li.each { linkItem ->
def link = linkItem.h3.a.@href
def address = linkItem.address.text()
println "$link: $address\n"
}
Run Code Online (Sandbox Code Playgroud)
然后你会得到的
#href1: Here is the addressTelephone number: telephone
#href2: Here is another addressAnother telephone: 0845 1111111
Run Code Online (Sandbox Code Playgroud)
grep返回一个ArrayList但find返回一个NodeChild类:
println html.'**'.grep { it.@class == 'divclass' }.getClass()
println html.'**'.find { it.@class == 'divclass' }.getClass()
Run Code Online (Sandbox Code Playgroud)
结果是:
class java.util.ArrayList
class groovy.util.slurpersupport.NodeChild
Run Code Online (Sandbox Code Playgroud)
因此,如果您想使用grep,那么您可以将另外一个像这样嵌套,以便它可以工作
html.'**'.grep { it.@class == 'divclass' }.ol.li.each {
it.each { linkItem ->
def link = linkItem.h3.a.@href
def address = linkItem.address.text()
println "$link: $address\n"
}
}
Run Code Online (Sandbox Code Playgroud)
长话短说,在你的情况下,使用find而不是grep.
归档时间: |
|
查看次数: |
10543 次 |
最近记录: |