ann
ann

Reputation: 113

Python + Selenium: Path to driver

Is there any possibility to run Python + Selenium script without entering the path of an exe file in every single script in Python line:

driver = webdriver.Chrome().

The same question applies to "IE Driver", "Edge Driver" and "Gecko Driver". Can it be done by some general python class and should I create some additional file for it? Or is it a matter of Integrated Development Environment configuration?

I would be grateful for your expert word.

Upvotes: 4

Views: 25706

Answers (4)

Soorena
Soorena

Reputation: 4462

No matter which OS you use you have multiple options to achieve this.

  • first of all you can put driver file (like chromedriver.exe) in a relative folder to your python files. (this is what I normally do)

driver = webdriver.Chrome('../chromedriver.exe')

driver = webdriver.PhantomJS('../phantomjs.exe')

  • You can put address to chrome driver inside your PATH variable in Windows, Linux or ...

driver = webdriver.Chrome('chromedriver.exe')

driver = webdriver.PhantomJS('phantomjs.exe')

  • Also you can set an environment variable and always rely on that.

driver = webdriver.Chrome(os.environ.get('CHROME_DRIVER_PATH'))

driver = webdriver.PhantomJS(os.environ.get('PHANTOMJS_DRIVER_PATH'))

Upvotes: 3

Retna1
Retna1

Reputation: 1

Here's what worked for me. I put the driver file in the same folder as the app I'm coding and the line in the code looks like:

web = webdriver.Chrome('./chromedriver.exe')

Upvotes: -1

Shivam Mishra
Shivam Mishra

Reputation: 1439

You can change the source code. Just assign the value of executable_path to your chromedriver path. Let me explain -

When you "normally" type this -

driver = webdriver.Chrome(r"path\chromedriver.exe")

The WebDriver object initializes in its class. The class file is located at //selenium_folder/webdriver/chrome/webdriver.py. Inside it, if you notice the __init__ method, it takes an argument of executable_path. So you can simply do -

def __init__(self, executable_path="chromedriver", port=0,
                 options=None, service_args=None,
                 desired_capabilities=None, service_log_path=None,
                 chrome_options=None):

     executable_path = "path\chromedriver.exe"

This way, the following code will successfully run the driver -

driver = webdriver.Chrome()

Upvotes: 3

jordan23
jordan23

Reputation: 73

Yes, you have to store the driver in the PATH. for example mine is at C:\python\python(version)\lib\site-package\selenium\webdriver and then store the driver in the proper folder. Also make sure to add the path to your machines environmental variables.

Upvotes: 1

Related Questions