theycallmepix
theycallmepix

Reputation: 514

How to Merge chromedriver.exe with a python script that runs on selenium webdriver using pyinstaller?

As far as I know, it's possible to merge or add chromedriver.exe with a python script that runs on selenium webdriver using Pyinstaller with reference to this post asked by @Phillip.

Here's my code(python):

# importing packages / modules
import os
import service  # This module cannot be installed as it asks for Microsoft Visual C++ 14 to be isntalled on pc

from selenium import webdriver
from selenium.webdriver.chrome.options import Options

# Defining required functions that needs to be used again and again
def init_driver():
    chrome_path = os.path.join(os.path.dirname(__file__), 'selenium','webdriver','chromedriver.exe')
    service = service.Service(chrome_path)  # So, this cannot be used to merge it.
    path = webdriver.Chrome(service, options=Options())

driver = init_driver()

and the command that was given in cmd:

pyinstaller --noconfirm --onefile --console --icon "path/to/icon.ico" --add-binary "path/to/chrome/driver;./driver" "path/to/the/python/pythonscript.py"

Upvotes: 1

Views: 2371

Answers (1)

theycallmepix
theycallmepix

Reputation: 514

We need to keep in our mind these 2 things:

  • Pyinstaller options
  • path to driver in source code

Chromedriver.exe is a binary, so, we can add it to Pyinstaller using --add binary as I've mentioned in the question. So, our pyinstaller command in cmd would be this:

pyinstaller --noconfirm --onefile --console --icon "path/to/icon.ico" --add-binary "path/to/chrome/driver;./driver" "path/to/the/python/pythonscript.py"

Secondly, we need to modify the source code in such a way that, it doesnot harm our code neither in python console nor in executable after conversion. So, we need to change the driver_path code from

driver = webdriver.Chrome('path/to/chromedriver.exe', options=Options())

to something like this

import os
import sys

def resource_path(another_way):
    try:
        usual_way = sys._MEIPASS  # When in .exe, this code is executed, that enters temporary directory that is created automatically during runtime.
    except Exception:
        usual_way = os.path.dirname(__file__)  # When the code in run from python console, it runs through this exception.
    return os.path.join(usual_way, another_way)


driver = webdriver.Chrome(resource_path('./driver/chromedriver.exe'), options=Options())

We write that Exception part in order to make it work with python console. If running only in .exe format is the main goal, then we can ignore the Exception part also.

This code throws warning in the python console pointing to _MEIPASS as we're trying to access protected member from a class. Along with that, sys.pyi cannot find a reference to _MEIPASS is what is highlighted.

Upvotes: 2

Related Questions