您如何解析网页并提取所有 href 链接? [英] How do you parse a web page and extract all the href links?

查看:37
本文介绍了您如何解析网页并提取所有 href 链接?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在 Groovy 中解析一个网页并提取所有的 href 链接和相关的文本.

如果页面包含这些链接:

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

输出将是:

谷歌,http://www.google.com<br/>苹果,http://www.apple.com

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

解决方案

假设 XHTML 格式正确,提取 xml,收集所有标签,找到 'a' 标签,并打印出 href 和文本.

>

input = """<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()}, ${it.@href.text()}"}

I want to parse a web page in Groovy and extract all of the href links and the associated text with it.

If the page contained these links:

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

the output would be:

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

I'm looking for a Groovy answer. AKA. The easy way!

解决方案

Assuming well-formed XHTML, slurp the xml, collect up all the tags, find the 'a' tags, and print out the href and text.

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()}, ${it.@href.text()}"
}

这篇关于您如何解析网页并提取所有 href 链接?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆