使用poltergeist与代理?

时间:2013-04-29 12:26:12

标签: ruby capybara phantomjs poltergeist

我正在使用PhantomJS和poltergeist来模拟浏览器,但是我不确定如何在代码中指定代理:

require 'capybara'
require 'capybara/dsl'
require 'capybara/poltergeist'

task :experiment => :environment do
  Capybara.run_server = false
  Capybara.current_driver = :poltergeist
  Capybara.app_host = "http://something.com"
  include Capybara::DSL

  # set_proxy('12.13.14.15', '4521')

  visit('posts')
  page.include?('foo')
end

另外,出于某种原因,我在使用poltergeist时会得到未定义的方法page,有人可以提出建议吗?

2 个答案:

答案 0 :(得分:8)

您需要将--proxy选项传递给PhantomJS,请参阅the API docs

使用Poltergeist,您可以使用the :phantomjs_options configuration option为PhantomJS指定命令行选项。

把它放在一起:

Capybara.register_driver :poltergeist do |app|
  Capybara::Poltergeist::Driver.new(app, phantomjs_options: ["--proxy=12.13.14.15:4521"])
end

答案 1 :(得分:1)

尝试在控制器操作中运行它,因此当它将通过控制器级别进行控制时,它将更新新的代理ip。像这样

def index
    options = {
       :js_errors => false,
       :debug => true,
       :phantomjs => "/Users/Umer/Desktop/phantomjs-2.0.0-macosx/bin/phantomjs",
       #:phantomjs_options => ["--proxy=#{proxy.ip}:#{proxy.port}", "--proxy-auth=#{proxy.username}:#{proxy.password}"]
       :phantomjs_options => ["--proxy=88.150.136.178:3128"]
    }
    Capybara.register_driver :poltergeist do |app|
      Capybara::Poltergeist::Driver.new(app, options)
    end
    Capybara.default_driver = :poltergeist
    Capybara.javascript_driver = :poltergeist
    Capybara.default_wait_time = 20
    Capybara.ignore_hidden_elements = true
    Capybara.run_server = false
    Capybara.app_host = 'http://mxtoolbox.com'


    session = Capybara::Session.new(:poltergeist)

    session.visit('/WhatIsMyIP/')

    file = File.new("test3.html", "w+")
    file.write(session.body)
    file.close

    session.driver.quit
end