(更新:这个答案是从 Nokogiri 的 Angular 写的,但如果您正在寻找特定查询的 XPATH 或 CSS 语法,它也很有用。)
我喜欢 Nokogiri——它是从 XML 和 HTML 文档中提取元素的绝佳工具。网上的例子虽然不错,但大多是展示如何操作XML文档。
如何使用 Nokogiri 从 HTML 中提取链接和链接文本?
最佳答案
这是一个最初为响应 Getting attribute's value in Nokogiri to extract link URLs 而编写的小示例,以社区 Wiki 样式在此处提取,以便于引用。
以下是您在解析 HTTP 链接时可能会执行的一些常见操作,均显示在 css
中。和 xpath
语法。
从这个片段开始:
require 'rubygems'
require 'nokogiri'
html = <<HTML
<div id="block1">
<a href="http://google.com">link1</a>
</div>
<div id="block2">
<a href="http://stackoverflow.com">link2</a>
<a id="tips">just a bookmark</a>
</div>
HTML
doc = Nokogiri::HTML(html)
提取所有链接
我们可以使用xpath 或css 找到所有<a>
元素,然后仅保留具有 href
的元素属性:
nodeset = doc.xpath('//a') # Get all anchors via xpath
nodeset.map {|element| element["href"]}.compact # => ["http://google.com", "http://stackoverflow.com"]
nodeset = doc.css('a') # Get all anchors via css
nodeset.map {|element| element["href"]}.compact # => ["http://google.com", "http://stackoverflow.com"]
在上述情况下,.compact
是必要的,因为搜索 <a>
除了其他元素之外,元素还返回“只是一个书签”元素。
但我们可以使用更精确的搜索来查找包含 href
的元素属性:
attrs = doc.xpath('//a/@href') # Get anchors w href attribute via xpath
attrs.map {|attr| attr.value} # => ["http://google.com", "http://stackoverflow.com"]
nodeset = doc.css('a[href]') # Get anchors w href attribute via css
nodeset.map {|element| element["href"]} # => ["http://google.com", "http://stackoverflow.com"]
查找特定链接
在 <div id="block2">
中查找链接
nodeset = doc.xpath('//div[@id="block2"]/a/@href')
nodeset.first.value # => "http://stackoverflow.com"
nodeset = doc.css('div#block2 a[href]')
nodeset.first['href'] # => "http://stackoverflow.com"
如果您知道您只搜索一个链接,您可以使用 at_xpath
或 at_css
相反:
attr = doc.at_xpath('//div[@id="block2"]/a/@href')
attr.value # => "http://stackoverflow.com"
element = doc.at_css('div#block2 a[href]')
element['href'] # => "http://stackoverflow.com"
从相关文本中查找链接
如果您知道与链接关联的文本并想找到它的 url 怎么办?一点 xpath-fu(或 css-fu)就派上用场了:
element = doc.at_xpath('//a[text()="link2"]')
element["href"] # => "http://stackoverflow.com"
element = doc.at_css('a:contains("link2")')
element["href"] # => "http://stackoverflow.com"
从链接中查找文本
为了完整起见,以下是获取与特定链接关联的文本的方式:
element = doc.at_xpath('//a[@href="http://stackoverflow.com"]')
element.text # => "link2"
element = doc.at_css('a[href="http://stackoverflow.com"]')
element.text # => "link2"
有用的引用资料
除了广泛的Nokorigi documentation ,我在写这篇文章时遇到了一些有用的链接:
关于css - 如何使用 Nokogiri(以及 XPATH 和 CSS)提取 HTML 链接和文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39653384/