我们如何解析网页并提取所有href链接?

时间:2020-03-06 14:24:32  来源:igfitidea点击:

我想在Groovy中解析一个网页,并提取所有href链接以及与之相关的文本。

如果页面包含以下链接:

<a href="http://www.google.com">Google</a><br />
<a href="http://www.apple.com">Apple</a>

输出将是:

Google, http://www.google.com<br />
Apple, http://www.apple.com

我正在寻找Groovy的答案。又名简单的方法!

解决方案

快速的谷歌搜索发现了一个很好的可能性,TagSoup。

尝试一个正则表达式。这样的事情应该起作用:

(html =~ /<a.*href='(.*?)'.*>(.*?)<\/a>/).each { url, text -> 
    // do something with url and text
}

看一下Groovy教程4正则表达式基础知识和Anchor Tag正则表达式破坏。

使用XMLSlurper将HTML解析为XML文档,然后使用带有适当闭包的find方法来选择a标签,然后在GPathResult上使用list方法来获取标签列表。然后,我们应该能够将文本提取为GPathResult的子级。

我不懂Java,但我认为xpath要获得一个(或者多个)html元素要比经典正则表达式好得多。

编写和阅读也更容易。

<html>
   <body>
      <a href="1.html">1</a>
      <a href="2.html">2</a>
      <a href="3.html">3</a>
   </body>
</html>

使用上面的html,此表达式" / html / body / a"将列出所有href元素。

这是一个很好的分步教程http://www.zvon.org/xxl/XPathTutorial/General/examples.html

假设格式正确的XHTML,则对XML进行过滤,收集所有标签,找到" a"标签,然后打印href和文本。

input = """<html><body>
<a href = "http://www.hjsoft.com/">John</a>
<a href = "http://www.google.com/">Google</a>
<a href = "http://www.stackoverflow.com/">StackOverflow</a>
</body></html>"""

doc = new XmlSlurper().parseText(input)
doc.depthFirst().collect { it }.findAll { it.name() == "a" }.each {
    println "${it.text()}, ${[email protected]()}"
}

HTML解析器+正则表达式
任何语言都可以做到,尽管我会说Perl是最快的解决方案。