はじめに
本記事では、seleniumライブラリを含めて、pyinstallerでEXE化する (Selenium4.Xで記載)。
なお、EXEにはChrome DriverやChromeブラウザーは含めない。
Chrome Driverはwebdriver-managerライブラリによってChromeブラウザーバージョンにあったものを取得させる。
コード
import os from selenium import webdriver from selenium.webdriver.chrome.service import Service from webdriver_manager.chrome import ChromeDriverManager import time def set_os_proxy_setting(proxy_server : str): # スクリプト内で環境変数をセットする os.environ["http_proxy"] = proxy_server os.environ["https_proxy"] = proxy_server os.environ["no_proxy"] = 'localhost,127.0.0.1' def main(): # WebDriver のオプションを設定する # https://qiita.com/skimhiro/items/de501f45607d6a09cde5 options = webdriver.ChromeOptions() options.add_argument("--no-sandbox") options.add_argument("--disable-gpu") options.add_argument("--ignore-certificate-errors") options.add_argument("--start-maximized") options.add_experimental_option('excludeSwitches', ['enable-logging']) # Selenium Chrome Proxy の設定 # PROXY_IP_ADDRESS_AND_PORT = "http://192.168.0.100:8080" # set_os_proxy_setting(PROXY_IP_ADDRESS_AND_PORT) # PROXY_AUTH = '{userid}:{password}' # options.add_argument(f"--proxy-server={PROXY_IP_ADDRESS_AND_PORT}") # options.add_argument(f"--proxy-auth={PROXY_AUTH}") # driverを生成する service=Service(ChromeDriverManager().install()) driver = webdriver.Chrome(service=service, options=options) # スクレイピングを実行する driver.get("https://qiita.com/") time.sleep(3) driver.close() driver.quit() if __name__ == "__main__": main()
specファイル (selenium-automation.spec)
# -*- mode: python ; coding: utf-8 -*- block_cipher = None a = Analysis( ['main.py'], pathex=[], binaries=[], datas=[], hiddenimports=["selenium", "webdriver-manager"], hookspath=[], hooksconfig={}, runtime_hooks=[], excludes=[], win_no_prefer_redirects=False, win_private_assemblies=False, cipher=block_cipher, noarchive=False, ) pyz = PYZ(a.pure, a.zipped_data, cipher=block_cipher) exe = EXE( pyz, a.scripts, a.binaries, a.zipfiles, a.datas, [], name='selenium-automation', debug=False, bootloader_ignore_signals=False, strip=False, upx=True, upx_exclude=[], runtime_tmpdir=None, console=False, disable_windowed_traceback=False, argv_emulation=False, target_arch=None, codesign_identity=None, entitlements_file=None, )