0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Selenium Proxyの設定はどこに書くのが正解なんですかねぇ、、という話

0
Last updated at Posted at 2021-03-09

Deprecation Warning

Selenimu + browsermob-proxyの動作をいろいろ試してみて。
いくつかのサイトを参考にさせていただくと、一回profileを作成し、そこにproxyとしてbrowsermod-proxyを設定し、それをwebdriverに食わせる、という方法を取ります。

それはそれでちゃんと動くのですが、以下のアラートが出ます。

"This method has been deprecated. Please pass in the proxy object to the Driver Object",

「その機能、使わせてはあげるけど、新しい方法用意してあるからそっち使ってね」というものですね。
じゃぁ、ちゃんと正しい方法とやらを使ってみますか、、と思ったらそうは行かなかったという話です。

言うとおりにしてみると、、

profile経由でproxy設定を与える場合、こんな感じになります。

from browsermobproxy import Server
from selenium import webdriver

# browsermob-proxyの設定
server = Server("./browsermob-proxy-2.1.4/bin/browsermob-proxy")
server.start()
proxy = server.create_proxy()

# proxyleの設定
profile = webdriver.FirefoxProfile()
profile.set_proxy(proxy.selenium_proxy())

# profile経由で、webdriverにproxyを設定
dirver = webdriver.Firefox(firefox_profile=profile)

一方、(おそらく)推奨の方法だと。

# 直接webdriverにproxyを設定
dirver = webdriver.Firefox(proxy=proxy.selenium_proxy())

で、コレで実行すると、、、browsermob-proxyからharが出せない!!
seleniumがproxy通さずに通信しちゃってるっぽい。。。。

実際にコードを見てみると、、
一応ifの一部条件ではproxyの値を参照するのだけど、保持してない=使ってないっぽいですね。。
https://github.com/SeleniumHQ/selenium/blob/selenium-3.141.0/py/selenium/webdriver/firefox/webdriver.py

結局どうすりゃいいのさ、、

pipで導入されるバージョンは3.141.0で、最新のバージョンだと4.0系があるのですが、これ4.0系でもwebdriverが引数で取るproxyは、取るだけ取って使ってないっぽい。。
4.0だとそもそもprofile自体が非推奨になり、optionsを使うようになるのですが、こちらもprofile同様にproxyの値を受け取れます。

seleniumを最新の4.0.0b1にあげて、optionにproxyを与えて、それをwebdriverに食わす方法を取ると、、OK。

$ pip3 install -U selenum=4.0.0b1
from browsermobproxy import Server
from selenium import webdriver


server = Server("./browsermob-proxy-2.1.4/bin/browsermob-proxy")
server.start()
proxy = server.create_proxy()

options = webdriver.FirefoxOptions()
options.set_preference('browser.privatebrowsing.autostart', True)
options.set_preference('browser.privatebrowsing.dont_prompt_on_enter', True)

proxy=proxy.selenium_proxy())
options.proxy = proxy.selenium_proxy()
driver = webdriver.Firefox(options=options)

ちゃんとproxy通る通信になるし、Deprecationエラー”は”、でなくなりますね。
でも、今度はchardetとurllib3のバージョンが、OS側とpip側で会ってないよというアラートが。。
ちなみにこれselenium 3.141.0で実行すると、optionでエラーが出て、実行できません。

まとめ

まぁアラートの話なので、無視するとわりきりゃいいっちゃいいんですけどね、、
Depricatedって言うなら、正しい方法ちゃんと動くようにしてからにしてほしいなぁという話でした。
私が意味取り違えてるのかもしれませんけれど、なんともなぁ。。

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?