LoginSignup
1
1

More than 3 years have passed since last update.

Vagrantを使って起動した仮想マシン(ubuntu)からWindowsのChromeを自動操作したい

Posted at

やりたいこと

Vagrantを使用して起動した仮想マシン上(ubuntu)のSelenium(python)から、ホスト(仮想マシンを実行しているWindows10)上のChromeにリモートアクセスする。

環境

仮想マシン側
  • ubuntu(64bit) 18.04.5(LTS)
  • python 3.8.0
  • selenium 3.141.0
ホスト側
  • virtual box 6.1.16
  • vagrant 2.2.14
  • chromedriver 87.0.4280.88

問題のある操作

前提
  • 事前にvagrantfileの設定がなされ、vagrant upによって仮想マシンが起動している。
  • 接続した仮想マシン(ubuntu)上にpythonの実行環境があり、必要なライブラリ(selenium等)がインストールされている。
  • seleniumでブラウザを自動操作する際に必要となるドライバ(今回はchromedriver)がインストールされている。
操作

1.ホスト上のWindows Power Shell(chromedriverがカレントディレクトリにある状態)で以下のコードを実行

.\chromedriver.exe --port=4444

2.vagrant上にある以下のpythonコードを実行する。

test.py
from selenium.webdriver import Chrome, ChromeOptions, Remote

options = ChromeOptions()
driver = Remote('http://10.0.2.2:4444', options=options)
#以下省略

3.以下のようなエラーが出力される

Traceback (most recent call last):
  File "test.py", line 4, in <module>
    driver = Remote('http://10.0.2.2:4444', options=options)
#中略
  File "/home/vagrant/scraping/lib/python3.8/site-packages/selenium/webdriver/remote/errorhandler.py", line 
208, in check_response
    raise exception_class(value)
selenium.common.exceptions.WebDriverException: Message: Host header or origin header is specified and is not whitelisted or localhost.

また、ホスト側で実行しているchromedriverでは以下のようなログが吐き出されている。

[1610458155.162][SEVERE]: Rejecting request with host: 10.0.2.2:4444. origin is

原因

chromedriverのデフォルト設定では、ローカルからの接続しか許容しない。

対策

リモートホストからの接続を許可するためには、chromedriver実行時の
コマンドに --allowed-ipsを付加してやればよい。

.\chromedriver.exe --port=4444  --allowed-ips

ホスト側でchromedriverを実行している状態で、再度仮想マシン上のpythonコードを実行してやれば、仮想マシンのubuntuからWindowsのChromeを自動操作できる!

参考

紹介した方法はchromedriverの公式ドキュメントに記載されています。
*セキュリティ上の考慮点にも言及しています。
https://chromedriver.chromium.org/security-considerations

Seleniumに関する知識は以下のサイトで入手可能
https://www.selenium.dev/documentation/ja/

1
1
0

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
1
1