gpt4 book ai didi

ruby - 从链接文本中提取带有 Nokogiri 的链接?

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

我想从网页中提取特定链接,使用 Nokogiri 按文本搜索它:

<div class="links">
<a href='http://example.org/site/1/'>site 1</a>
<a href='http://example.org/site/2/'>site 2</a>
<a href='http://example.org/site/3/'>site 3</a>
</div>

我想要“站点 3”的 href 并返回:

http://example.org/site/3/

或者我想要“站点 1”的 href 并返回:

http://example.org/site/1/

我该怎么做?

最佳答案

原文:

text = <<TEXT
<div class="links">
<a href='http://example.org/site/1/'>site 1</a>
<a href='http://example.org/site/2/'>site 2</a>
<a href='http://example.org/site/3/'>site 3</a>
</div>
TEXT

link_text = "site 1"

doc = Nokogiri::HTML(text)
p doc.xpath("//a[text()='#{link_text}']/@href").to_s

更新:

据我所知,Nokogiri 的 XPath 实现不支持正则表达式,对于基本的 starts with 匹配,有一个名为 starts-with 的函数,您可以像这样使用(以“s”开头的链接):

doc = Nokogiri::HTML(text)
array_of_hrefs = doc.xpath("//a[starts-with(text(), 's')]/@href").map(&:to_s)

关于ruby - 从链接文本中提取带有 Nokogiri 的链接?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14101985/

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