LoginSignup
28
25

More than 3 years have passed since last update.

Seleniumでnavigator.webdriverの対策をしてアクセスする

Last updated at Posted at 2020-07-01

enable-automationとかuseAutomationExtensionは期待通りの動作しなかった

とある理由でスクレイピングしたいけど、navigator.webdriver=trueなブラウザだとNGなサイトだった。
対応したい。できるらしいので。
参考:navigator.webdriver=trueだとロボットだとバレる。その回避法はあるか?puppeteerなら出来そう

でもSelenium使っているしpuppeteer使ったことないし、どうにかできないものか。。

動かなかったときの設定

どうやらSeleniumでもできるらしい記事をいくつか見つけた。

参考1:https://stackoverflow.com/questions/53039551/selenium-webdriver-modifying-navigator-webdriver-flag-to-prevent-selenium-detec

参考2:https://help.applitools.com/hc/en-us/articles/360007189411--Chrome-is-being-controlled-by-automated-test-software-notification

やってみた。

    capabilities = Selenium::WebDriver::Remote::Capabilities.chrome(
      accept_insecure_certs: true,
      chromeOptions: {
        args: [
          '-window-size=1920,1080',
          '--user-agent=Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Safari/537.36'
        ],
        excludeSwitches: ['enable-automation'], # 追加
        useAutomationExtension: false # 追加
      }
    )
    driver = Selenium::WebDriver.for(
      :remote,
      url: 'http://chrome:4444/wd/hub',
      desired_capabilities: capabilities,
      http_client: Selenium::WebDriver::Remote::Http::Default.new
    )

実際に動かしてみてもtrueが帰ってくる。ダメだった。

driver.execute_script('return navigator.webdriver')
>>> true

動いた設定

enable-automationとかuseAutomationExtensionは削除。
今まで通りにdriverを設定。

    capabilities = Selenium::WebDriver::Remote::Capabilities.chrome(
      accept_insecure_certs: true,
      chromeOptions: {
        args: [
          '-window-size=1920,1080',
          '--user-agent=Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Safari/537.36'
        ],
      }
    )
    driver = Selenium::WebDriver.for(
      :remote,
      url: 'http://chrome:4444/wd/hub',
      desired_capabilities: capabilities,
      http_client: Selenium::WebDriver::Remote::Http::Default.new
    )

    # 以下を追加
    driver.execute_script('const newProto = navigator.__proto__;delete newProto.webdriver;navigator.__proto__ = newProto;')

実際に動かすとundefinedが帰ってくる。
puppeteerと似たような動作する。
良かった。

driver.execute_script('return navigator.webdriver')
>>> undefined
28
25
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
28
25