问题
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 driverinside yourPATHvariable 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