在Heroku上使用Mechanize时出现403错误

时间:2014-08-27 15:51:06

标签: ruby heroku web-scraping mechanize mechanize-ruby

当使用mechanize从craigslist中提取一些数据时,我在Heroku上不断收到以下错误:status: Net::HTTPForbidden 1.1 403 Forbidden

我想知道有什么方法可以防止这种情况发生,我的设置如下:

agent = Mechanize.new do |agent|
  agent.log              = @logger
  agent.user_agent_alias = 'Mac Safari'
  agent.robots           = false
end

有什么想法吗?

2 个答案:

答案 0 :(得分:3)

想象一下,这会让它更清洁一些。我有同样的问题,我可以通过请求新的标题来解决:

@agent = Mechanize.new { |agent|
                      agent.user_agent_alias = 'Windows Chrome'}


@agent.request_headers

如果您还没有,还应该包含一些错误处理。我写了以下内容来提出一个想法:

begin  #beginning of block for handling rescue
              @results_page = #getting some page and doing cool stuff
         #The following line puts mechanize to sleep when a new page is reached for 1/10 second.  This keeps you from overloading the site you're scraping and minimizing the chance of getting errors.  If you start to get '503' errors you should increase this number a little!
              @agent.history_added = Proc.new {sleep 0.1}

            rescue Mechanize::ResponseCodeError => exception
              if exception.response_code == "503"
                @agent.history_added = Proc.new {sleep .2}
              #the following line closes all active connections
                @agent.shutdown
                @agent = Mechanize.new { |agent|
                  agent.user_agent_alias = 'Windows Chrome'}
                @agent.request_headers
                @page = @agent.get('the-webpage-i-wanted.com')
                @form = @page.#GettingBackToWhereIWas
                redo 
                else
                #more error handling if needed
                end

***注意:考虑将此作为后台进程运行,以避免heroku上的超时错误,因为它们只允许15-30秒的请求 - 响应周期。如果您还没有使用redisToGo(heroku插件)和sidekiq(dl gem),我会使用它!

答案 1 :(得分:0)

使用机械化和其他此类浏览器模拟器时,您必须监控网络,我更喜欢使用Google Chrome开发人员工具。

使用普通浏览器检查您的网址并查看以下内容:

  1. 此网址有效吗?
  2. 这个网址是公开的吗?
  3. 此网址浏览器是否受限制?
  4. 此网址是否通过登录保护?
  5. 此网址在正常情况下会有哪些参数?
  6. 调试这些点,因为您访问的URL可能限制为:

    • 公共使用
    • 可能是目录路径,不允许索引
    • 可能是服务器限制了某些用户代理
    • 可能是你没有完全复制请求

    我想我使用了太多“可能”但我的观点是,如果你不能公开发布你的链接我可以猜测你的错误,如果你的链接直接命中一个目录并且它的索引关闭那么你无法在机械化中浏览它,如果是针对特定用户代理,那么您应该使用特定的用户代理初始化您的机械化,如:

    browser = Mechanize.new
    browser.user_agent_alias = 'Windows IE 7'
    

    在任何其他情况下,您没有复制您的请求,或者某些重要参数丢失,或者您发送了错误的请求类型,标题可能会丢失。

    编辑:现在您已经提供了链接,这是您在处理https时应该做的事情

    Mechanize.new{|a| a.ssl_version, a.verify_mode = 'SSLv3', OpenSSL::SSL::VERIFY_NONE};