如何获取HTML页面的当前URL

问题描述 投票:1回答:2

我正在使用Nokogiri抓取网站。该特定网站处理绝对URL的方式有所不同。

如果我给它一个类似的URL:

page = Nokogiri::HTML(open(link, :allow_redirections => :all))

它将重定向到HTTPS版本,也重定向到URL的长版本。例如,类似

的链接
http://www.website.com/name

变成

http://www.website.com/other-area/name

这很好,并没有真正影响我的刮板,但是,在某些极端情况下,如果我可以告诉刮板当前的URL是什么,我可以避免它们。

在将上面的链接传递到我的page变量后,重定向发生后如何获取该页面的当前URL?

ruby nokogiri
2个回答
1
投票

[我假设您正在使用open_uri_redirections gem,因为在Ruby 2.4+中不需要:allow_redirections

保存OpenURI的open的结果:

require 'open-uri'
r = open('http://www.google.com/gmail')
r.base_uri
# #<URI::HTTPS https://accounts.google.com/ServiceLogin?service=mail&passive=true&rm=false&continue=https://mail.google.com/mail/&ss=1&scc=1&ltmpl=default&ltmplcache=2&emr=1&osid=1#>
page = Nokogiri::HTML(r)

2
投票

使用机械化,则可以执行:

agent = Mechanize.new
page = agent.get url
puts page.uri # this will be the redirected url
© www.soinside.com 2019 - 2024. All rights reserved.