如何通过Nokogiri从HTML代码获取邮件地址?我正在考虑正则表达式,但我不知道它是否是最好的解决方案.
示例代码
<html>
<title>Example</title>
<body>
This is an example text.
<a href="mailto:example@example.com">Mail to me</a>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)
我的问题是,如果在某个标签之间不存在,则在nokogiri中存在获取邮件地址的方法.
谢谢
mat*_*att 11
您可以使用xpath提取电子邮件地址.
选择器//a将选择a页面上的任何标签,您可以href使用@语法指定属性,因此//a/@href将为您提供页面上href所有a标签的s .
如果a页面上有可能的标签混合使用不同的网址类型(例如http://网址),则可以使用xpath函数进一步缩小所选节点的范围.选择器
//a[starts-with(@href, \"mailto:\")]/@href
Run Code Online (Sandbox Code Playgroud)
将为您提供a具有href以"mailto:"开头的属性的所有标记的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
Run Code Online (Sandbox Code Playgroud)
使用如下所示的测试文件:
<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>
Run Code Online (Sandbox Code Playgroud)
此代码输出所需的example@example.com.addresses是文档中mailto链接中所有电子邮件地址的数组.