【问题标题】:Detect redirect with ruby mechanize使用 ruby​​ mechanize 检测重定向
【发布时间】:2013-07-04 09:21:12
【问题描述】:

我正在使用 mechanize/nokogiri gem 来解析一些随机页面。我遇到了 301/302 重定向问题。这是代码的sn-p:

agent = Mechanize.new
page = agent.get('http://example.com/page1')

mydomain.com 上的测试服务器会将 page1 重定向到 page2 并带有 301/302 状态码,因此我期待有

page.code == "301"

相反,我总是得到page.code == "200"

我的要求是:

  • 我希望遵循重定向(默认机械化行为,这很好)
  • 我希望能够检测到该页面实际上被重定向了

我知道我可以在agent.history 中看到page1,但这并不可靠。我也想要重定向状态码。

如何通过机械化实现这种行为?

【问题讨论】:

    标签: ruby http redirect mechanize


    【解决方案1】:

    您可以关闭重定向并继续关注位置标头:

    agent.redirect_ok = false
    page = agent.get 'http://www.google.com'
    status_code = page.code
    
    while page.code[/30[12]/]
      page = agent.get page.header['location']
    end
    

    【讨论】:

    • 也许是你,但 OP 要求它。
    【解决方案2】:

    我找到了一种允许重定向并获取状态码的方法,但我不确定这是不是最好的方法。

    agent = Mechanize.new
    
    # deactivate redirects first
    agent.redirect_ok = false
    
    status_code = '200'
    error_occurred = false
    
    # request url
    begin
      page = agent.get(url)
      status_code = page.code
    rescue Mechanize::ResponseCodeError => ex
      status_code = ex.response_code
      error_occurred = true
    end
    
    if !error_occurred && status_code != '200' then
      # enable redirects and request the page again
      agent.redirect_ok = true
      page = agent.get(url)
    end
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-03-19
      • 2011-02-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-02-11
      • 1970-01-01
      相关资源
      最近更新 更多