groovy - 从groovy中的href-tag中提取URL

标签 groovy xmlslurper tag-soup

我需要解析格式错误的 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/

相关文章:

groovy - 在 Groovy 中使用 XmlSlurper 读取 XML 元素

grails - 如何访问 Grails 2.0 中的 Grails 配置?

grails - 使用XmlSlurper解析时如何使用带点的配置条目

java - mkp.yieldUnescaped 不起作用

xml - Groovys XmlSlurper 中的命名空间处理

java - Groovy 使用字符串获取 json slurper 对象中的对象

java - JDOM 1.1 : hyphen is not a valid comment character

jaxb - 如何在 HTML 中使用 JAXB?

java - 使用 zip4j 损坏 NiFi ExecuteScript 输出