使用Nokogiri提取链接时如何获取绝对URL?

Mri*_*lla 25 ruby nokogiri

我正在使用Nokogiri从页面中提取链接,但我想获得绝对路径,即使页面上的链接是相对路径.我怎么能做到这一点?

Phr*_*ogz 57

Nokogiri是无关紧要的,除了它为你提供了链接锚点.使用Ruby的URI库来管理路径:

absolute_uri = URI.join( page_url, href ).to_s
Run Code Online (Sandbox Code Playgroud)

看到行动:

require 'uri'

# The URL of the page with the links
page_url = 'http://foo.com/zee/zaw/zoom.html'

# A variety of links to test.
hrefs = %w[
  http://zork.com/             http://zork.com/#id
  http://zork.com/bar          http://zork.com/bar#id
  http://zork.com/bar/         http://zork.com/bar/#id
  http://zork.com/bar/jim.html http://zork.com/bar/jim.html#id
  /bar                         /bar#id
  /bar/                        /bar/#id
  /bar/jim.html                /bar/jim.html#id
  jim.html                     jim.html#id
  ../jim.html                  ../jim.html#id
  ../                          ../#id
  #id
]

hrefs.each do |href|
  root_href = URI.join(page_url,href).to_s
  puts "%-32s -> %s" % [ href, root_href ]
end
#=> http://zork.com/                 -> http://zork.com/
#=> http://zork.com/#id              -> http://zork.com/#id
#=> http://zork.com/bar              -> http://zork.com/bar
#=> http://zork.com/bar#id           -> http://zork.com/bar#id
#=> http://zork.com/bar/             -> http://zork.com/bar/
#=> http://zork.com/bar/#id          -> http://zork.com/bar/#id
#=> http://zork.com/bar/jim.html     -> http://zork.com/bar/jim.html
#=> http://zork.com/bar/jim.html#id  -> http://zork.com/bar/jim.html#id
#=> /bar                             -> http://foo.com/bar
#=> /bar#id                          -> http://foo.com/bar#id
#=> /bar/                            -> http://foo.com/bar/
#=> /bar/#id                         -> http://foo.com/bar/#id
#=> /bar/jim.html                    -> http://foo.com/bar/jim.html
#=> /bar/jim.html#id                 -> http://foo.com/bar/jim.html#id
#=> jim.html                         -> http://foo.com/zee/zaw/jim.html
#=> jim.html#id                      -> http://foo.com/zee/zaw/jim.html#id
#=> ../jim.html                      -> http://foo.com/zee/jim.html
#=> ../jim.html#id                   -> http://foo.com/zee/jim.html#id
#=> ../                              -> http://foo.com/zee/
#=> ../#id                           -> http://foo.com/zee/#id
#=> #id                              -> http://foo.com/zee/zaw/zoom.html#id
Run Code Online (Sandbox Code Playgroud)

这里以前使用的答案比较复杂URI.parse(root).merge(URI.parse(href)).to_s.
感谢@pguardiario的改进.

  • Nokogiri可能与此有关.方法如下:如果html文档包含基本标记,则上述解决方案将无法正常工作.在这种情况下,应该使用基本标记的href属性的值而不是page_url.看看@ david-thomas在这里更详细的解释:http://stackoverflow.com/questions/5559578/havling-links-relative-to-root (5认同)

pgu*_*rio 15

Phrogz的答案很好,但更简单:

URI.join(base, url).to_s
Run Code Online (Sandbox Code Playgroud)

  • 你能给出一个基数和网址的例子吗? (2认同)
  • `base ="http://www.google.com/somewhere"; url ='/ over/there';`我相信pguardino的变量名称有点不精确 (2认同)