加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

ruby – 如何使用Nokogiri从HTML代码中获取邮件地址?

发布时间:2020-12-17 03:59:56 所属栏目:百科 来源:网络整理
导读:如何通过Nokogiri从 HTML代码获取邮件地址?我正在考虑正则表达式,但我不知道它是否是最好的解决方案. 示例代码 htmltitleExample/titlebodyThis is an example text.a href="mailto:example@example.com"Mail to me/a/body/html 我的问题是,如果在某个标签
如何通过Nokogiri从 HTML代码获取邮件地址?我正在考虑正则表达式,但我不知道它是否是最好的解决方案.

示例代码

<html>
<title>Example</title>
<body>
This is an example text.
<a href="mailto:example@example.com">Mail to me</a>
</body>
</html>

我的问题是,如果在某个标签之间不存在,则在nokogiri中存在获取邮件地址的方法.

谢谢

解决方法

您可以使用xpath提取电子邮件地址.

选择器// a将选择页面上的任何标签,您可以使用@语法指定href属性,因此// a / @ href将为您提供页面上所有标签的href.

如果页面上有可能的标签混合使用不同的网址类型(例如http:// urls),则可以使用xpath函数进一步缩小所选节点的范围.选择器

//a[starts-with(@href,"mailto:")]/@href

将为您提供具有以“mailto:”开头的href属性的所有标记的href节点.

把这一切放在一起,并添加一些额外的代码,从属性值的开头去掉“mailto:”:

require 'nokogiri'

selector = "//a[starts-with(@href,"mailto:")]/@href"

doc = Nokogiri::HTML.parse File.read 'my_file.html'

nodes = doc.xpath selector

addresses = nodes.collect {|n| n.value[7..-1]}

puts addresses

使用如下所示的测试文件:

<html>
<title>Example</title>
<body>
This is an example text.
<a href="mailto:example@example.com">Mail to me</a>
<a href="http://example.com">A Web link</a>
<a>An empty anchor.</a>
</body>
</html>

此代码输出所需的example@example.com.地址是文档中mailto链接中所有电子邮件地址的数组.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读