@Satoh_D no blog

大分にUターンしたので記念に。調べたこととか作ったこととか食べたこととか

【Selenium】MaxRetryErrorの後Connection Refusedエラーとなる場合の解決方法

Selenium を使って複数サイトのスクリーンショットを撮りたく、以下のようなコードを書いて実行したら Connection resused というエラーが出てしまった。

【書いたコード(例)】

from selenium import webdriver
import chromedriver_binary

def capture_site_a(driver):
    driver.get('https://example.com/a')
    ...
    driver.save_screenshot('foo.png')
    driver.quit()

def capture_site_b(driver):
    driver.get('https://example.com/b')
    ...
    driver.save_screenshot('bar.png')
    driver.quit()

if __name__ == '__main__':
    options = webdriver.ChromeOptions()
    options.add_argument('--headless')
    options.add_argument('--window-size=2560,1440')
    driver = webdriver.Chrome(options=options)

    capture_site_a(driver)
    capture_site_b(driver)

【出力されたエラー】

urllib3.exceptions.MaxRetryError: HTTPConnectionPool(host='localhost', port=58302): Max retries exceeded with url: /session/952a07d3cc028002ae416fe63ff1c0af/url (Caused by NewConnectionError('<urllib3.connection.HTTPConnection object at 0x10cf6bee0>: Failed to establish a new connection: [Errno 61] Connection refused'))

前提

解決方法

webdriverの設定を最初に作成して使い回すのではなく、各関数(上記コードで言う capture_site_a, capture_site_b)の呼び出し時に初期化することでエラーが回避できた。

...
def setup_webdriver():
    options = webdriver.ChromeOptions()
    options.add_argument('--headless')
    options.add_argument('--window-size=2560,1440')
    driver = webdriver.Chrome(options=options)

    return driver

def capture_site_a():
    driver = setup_webdriver()
    driver.get('https://example.com/a')
    ...
    driver.save_screenshot('foo.png')
    driver.quit()

def capture_site_b():
    driver = setup_webdriver()
    driver.get('https://example.com/b')
    ...
    driver.save_screenshot('bar.png')
    driver.quit()

他にも調べていると、各関数で driver.quit() していると後続処理で再度 driver.get() すると Connection refused が起きるみたいな記事もあった。
今回は上記手段で回避できたので、それでもダメそうだったら試してみる。

awesome03.com

参考サイト

qiita.com

awesome03.com