我需要解析格式错误的 HTML 页面并从中提取某些 URL 作为任何类型的集合。
我真的不在乎什么样的 Collection,我只需要能够迭代它。
假设我们有一个这样的结构:
<html>
<body>
<div class="outer">
<div class="inner">
<a href="http://www.google.com" title="Google">Google-Link</a>
<a href="http://www.useless.com" title="I don't need this">Blah blah</a>
</div>
<div class="inner">
<a href="http://www.youtube.com" title="Youtube">Youtube-Link</a>
<a href="http://www.useless2.com" title="I don't need this2">Blah blah2</a>
</div>
</div>
</body>
</html>
这是我到目前为止所做的:// tagsoup version 1.2 is under apache license 2.0
@Grab(group='org.ccil.cowan.tagsoup', module='tagsoup', version='1.2' )
XmlSlurper slurper = new XmlSlurper(new org.ccil.cowan.tagsoup.Parser());
GPathResult nodes = slurper.parse("test.html");
def links = nodes."**".findAll { it.@class == "inner" }
println links
我想要类似的东西["http://google.com", "http://youtube.com"]
但我得到的是:["Google-LinkBlah blah", "Youtube-LinkBlah blah2"]
更准确地说,我不能使用所有 URL,因为我需要解析的 HTML 文档大约有 15000 行,并且有很多我不需要的 URL。
所以我需要 第一 每个“内部”块中的 URL。
最佳答案
正如 The Trav 所说,您需要获取 href
每个匹配的属性 a
标签。
您已经编辑了您的问题,因此 class
位在 findAll
没有意义,但是对于当前的 HTML 示例,这应该可以工作:
def links = nodes.'**'.findAll { it.name() == 'a' }*.@href*.text()
编辑
如果(如您编辑后所说)您只想要第一个
a
在任何标有 class="inner"
的东西里面,然后尝试:def links = nodes.'**'.findAll { it.@class?.text() == 'inner' }
.collect { d -> d.'**'.find { it.name() == 'a' }?.@href }
.findAll() // remove nulls if there are any
关于groovy - 从groovy中的href-tag中提取URL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15462896/