SeleniumでChormeのネットワーク情報を得ることで、CFDのリアルタイム価格を取り込むコードを以前使っていたんですが、動かなくなっていたので修正しました。その時のメモです。

原因は、SeleniumのUpdateらしい

Python のコードで動かなくなったら、大抵なんかがUpdateしてるんだけど、今回もそれっぽい。selenium-webdriver がアップデートして、使い方が変更されたみたい。元のコードは以下。

# ----------- chrome webDriver ----------- #
# 自動で最新バージョンをダウンロードしてパス名を返してくれる。
driver_path = ChromeDriverManager().install()
# chrome options
options = webdriver.ChromeOptions()

userDir = r'C:\Users\xxx\AppData\Local\Google\Chrome\User Data\Default'
profileDir = 'Profile 1'
options.add_argument('--user-data-dir=' + userDir)
options.add_argument('--profile-directory=' + profileDir)
        
options.add_argument('--headless')
options.add_argument('--no-sandbox')
options.add_argument('--disable-dev-shm-usage')
options.add_argument('--disable-gpu')
options.add_argument('--ignore-certificate-errors')
        
# make chrome log requests
capabilities = DesiredCapabilities.CHROME
# caps['goog:loggingPrefs']
capabilities["goog:loggingPrefs"] = {"performance": "ALL"}

# chrome service
service = Service(executable_path=driver_path)

self.driver = webdriver.Chrome(
    desired_capabilities= capabilities,
    service = service,
    options = options
)

発生エラー

エラーはというと、以下。 unexpected keyword argument だそうです。

self.driver = webdriver.Chrome(
TypeError: __init__() got an unexpected keyword argument 'desired_capabilities'

対処方法

webdriver内のdesired_apabilitiesの設定がなくなっているので、代替された何かがあるはず。ということで調べてみると、Optionsのset_capabilityで書き込めということらしい。

# ----------- chrome webDriver ----------- #
# 自動で最新バージョンをダウンロードしてパス名を返してくれる。
driver_path = ChromeDriverManager().install()
# chrome options
options = webdriver.ChromeOptions()

userDir = r'C:\Users\xxx\AppData\Local\Google\Chrome\User Data\Default'
profileDir = 'Profile 1'
options.add_argument('--user-data-dir=' + userDir)
options.add_argument('--profile-directory=' + profileDir)
        
options.add_argument('--headless')
options.add_argument('--no-sandbox')
options.add_argument('--disable-dev-shm-usage')
options.add_argument('--disable-gpu')
options.add_argument('--ignore-certificate-errors')
        
# 以下の部分を
# make chrome log requests
# capabilities = DesiredCapabilities.CHROME
# caps['goog:loggingPrefs']
#capabilities["goog:loggingPrefs"] = {"performance": "ALL"}
# 次のように変更
        
options.set_capability("goog:loggingPrefs", {"performance": "ALL"})
    
# chrome service
service = Service(executable_path=driver_path)

self.driver = webdriver.Chrome(
    #desired_capabilities= capabilities, <<この行は不要となる
    service = service,
    options = options
)