Using poltergeist with a proxy?

一世执手 提交于 2019-12-04 01:43:01

问题


I'm using PhantomJS and poltergeist to emulate a browser, however I'm not sure how to specify a proxy to use in the code:

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

Also, for some reason, i get undefined method page when using poltergeist, can anyone advise?


回答1:


You need to pass the --proxy option to PhantomJS, see the API docs

With Poltergeist, you can use the :phantomjs_options configuration option to specify command line options for PhantomJS.

Putting it together:

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



回答2:


Try to run it in controller action, so when it will control through controller level it will update the new proxy ip. Like this way

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


来源:https://stackoverflow.com/questions/16278597/using-poltergeist-with-a-proxy

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!