加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

ruby-on-rails – 使用OpenUri,如何获取重定向页面的内容?

发布时间:2020-12-17 04:31:57 所属栏目:百科 来源:网络整理
导读:我想从这个页面获取数据: http://www.canadapost.ca/cpotools/apps/track/personal/findByTrackNumber?trackingNumber=0656887000494793 但该页面转发到: http://www.canadapost.ca/cpotools/apps/track/personal/findByTrackNumber?execution=eXs1 因此,
我想从这个页面获取数据:
http://www.canadapost.ca/cpotools/apps/track/personal/findByTrackNumber?trackingNumber=0656887000494793

但该页面转发到:

http://www.canadapost.ca/cpotools/apps/track/personal/findByTrackNumber?execution=eXs1

因此,当我从OpenUri使用open来尝试获取数据时,它会抛出一个RuntimeError错误,说HTTP重定向循环:

我不确定如何在重定向并抛出该错误后获取该数据.

解决方法

你需要一个像 Mechanize这样的工具.从它的描述:

The Mechanize library is used for
automating interaction with websites.
Mechanize automatically stores and
sends cookies,follows redirects,can
follow links,and submit forms. Form
fields can be populated and submitted.
Mechanize also keeps track of the
sites that you have visited as a
history.

这正是你需要的.所以,

sudo gem install mechanize

然后

require 'mechanize'
agent = WWW::Mechanize.new
page = agent.get "http://www.canadapost.ca/cpotools/apps/track/personal/findByTrackNumber trackingNumber=0656887000494793"

page.content # Get the resulting page as a string
page.body # Get the body content of the resulting page as a string
page.search(".somecss") # Search for specific elements by XPath/CSS using nokogiri

而你已经准备好摇滚了.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读