首页 > 解决方案 > 具有代理身份验证的 Selenium Webdriver 无头 chrome

问题描述

我需要在我的无头 chrome 实现中使用经过身份验证的代理。这些是在 heroku dynos 上执行的作业(如果有更好的方法可以直接在 heroku dynos 上实现代理)。

如果我遵循 selenium 的标准代理实现,我会卡在要求用户名/密码的身份验证页面。

这就是我使用 watir 和 selenium 实例化无头 chrome 实例的方式:

def headless_browser
  options = Selenium::WebDriver::Chrome::Options.new

  # make a directory for chrome if it doesn't already exist
  chrome_dir = File.join Dir.pwd, %w(tmp chrome)
  FileUtils.mkdir_p chrome_dir
  options.add_argument "--user-data-dir=#{chrome_dir}"

  # set Random User Agent
  options.add_argument "--user-agent=#{random_user_agent}"

  # let Selenium know where to look for chrome if we have a hint from
  # heroku. chromedriver-helper & chrome seem to work out of the box on osx,
  # but not on heroku.
  if chrome_bin = ENV["GOOGLE_CHROME_BIN"]
    options.add_argument "no-sandbox"
    options.binary = chrome_bin

    # give a hint to webdriver here too
    Selenium::WebDriver::Chrome.driver_path = \
      '/app/vendor/bundle/bin/chromedriver'
  end

  options.add_argument '--allow-insecure-localhost'

  # headless!
  # keyboard entry wont work until chromedriver 2.31 is released
  options.add_argument '--window-size=1200x600'
  options.add_argument '--headless'
  options.add_argument '--disable-gpu'
  options.add_argument '--no-sandbox'

  # instantiate the browser
  browser = Watir::Browser.new :chrome, options: options

  if Rails.env.development?
    browser.goto "https://api.myip.com"
    JSON.parse(Nokogiri::HTML.parse(browser.html).css('body').text)
  end
end

有谁知道如何使用 watir 和 selenium 实现经过身份验证的代理使用?我进行了很多搜索并实施了很多不同的“解决方案”,但没有一个对我有用。

Selenium::WebDriver::Proxy.new(
  http: '127.0.0.1:8080',
  ssl:  '127.0.0.1:8080'
)

我还尝试了 socks 格式:username:password@host:port. 没用。

标签: seleniumselenium-webdriverselenium-chromedriverwatirgoogle-chrome-headless

解决方案


请尝试以下代码与您的代理设置:

proxy_object = Selenium::WebDriver::Proxy.new(
  http: '127.0.0.1:8080',
  ssl:  '127.0.0.1:8080'
)

browser = Watir::Browser.new :chrome, options: options, proxy: proxy_object

推荐阅读