2013-04-29 62 views
3

我使用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 

此外,由於某種原因,我得到了一個未定義的方法page時使用poltergeist,任何人都可以建議嗎?

回答

8

您需要的--proxy選項傳遞給PhantomJS,看到the API docs

用騷靈,您可以使用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 
+0

這怎麼可以在每個請求的基礎上完成? – Hendrik 2017-09-19 15:59:58

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