0

我正在尝试抓取一些看起来像这样的 DOM:

<span>text</span>

有时看起来像这样:

<span><p>text</p></span>

但是,我似乎无法弄清楚如何进入text第二种情况。我尝试了几种方法,这就是我认为应该在下面起作用的方法:

def html = slurper.parse(reader)
Collection<NodeChild> nodes = html.'**'.findAll { it.name() == 'span' && it.@class == 'style2' }
...
def descriptionNode = html.'**'.find { it.name() == 'span' && it.@class == 'style20' }
def innerNode = descriptionNode.'**'.find { it.name() == 'p' }
def description
if (innerNode?.size() > 0)
{
description = innerNode.text()
}
else
{
description = descriptionNode.text()
}

知道我需要如何使用 xmlslurper 来获得我需要的行为吗?

4

3 回答 3

3

听起来您想检查给定是否span包含嵌套的p. 您可以遍历span节点的子节点以检查这种情况。例子:

def xml = """
<test>
  <span>test1</span>
  <span><p>test2</p></span>
  <other><span>test3</span></other>
  <other><span><p>test4</p></span></other>
</test>
"""

def doc = new XmlSlurper().parseText(xml)
def descriptions = []
doc.'**'.findAll { it.name() == 'span' }.each { node ->
    if (node.children().find { it.name() == 'p' }) {
            descriptions << node.p.text()
    } else {
            descriptions << node.text()
    }
}
assert descriptions == ['test1', 'test2', 'test3', 'test4']
于 2011-01-24T06:35:15.297 回答
0

您是否尝试过 xpath: //span/text()?您可能需要查询两次以说明 p 标记。

于 2011-01-24T06:08:28.673 回答
0

事实证明,HTML 一定是无效的。标签汤已创建

<div>
<span>
</span>
<p></p>
</div>

但萤火虫显示

<div>
<span>
<p></p>
</span>
</div>

多么可怕的错误。

于 2011-01-25T02:25:20.097 回答