gpt4 book ai didi

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

转载 作者:数据小太阳 更新时间:2023-10-29 07:23:16 26 4
gpt4 key购买 nike

如何使用 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 将选择页面上的任何 a 标签,您可以使用 @ 指定 href 属性 语法,因此 //a/@href 将为您提供页面上所有 a 标记的 href

如果页面上可能混合了具有不同 url 类型(例如 http:// url)的 a 标记,您可以使用 xpath 函数进一步缩小范围选定的节点。选择器

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

将为您提供所有 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

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

<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.comaddresses 是文档中 mailto 链接中所有电子邮件地址的数组。

关于ruby - 如何使用 Nokogiri 从 HTML 代码中获取邮件地址,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9492259/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com