Python + Selenium: Path to driver

天涯浪子 提交于 2019-12-24 14:36:59

问题


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.


回答1:


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()



回答2:


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

  • first of all you can put driver file (like chorme_driver.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'))




回答3:


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.



来源:https://stackoverflow.com/questions/48581090/python-selenium-path-to-driver

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!