Selenium自动化测试-driver的使用

webdriver的使用

以下以Edge的驱动为例,Chrome、Firefox一样。

from selenium import webdriver

方式一
# 调用浏览器的驱动,使用指定驱动路径的方式
driver = webdriver.Edge(executable_path="C:\\Program Files (x86)\\Microsoft\\Edge\\Application\\msedgedriver.exe")

方式二
# 将浏览器driver所在的路径放到环境变量$PATH中,例如"c:\drivers\",之后就可以直接调用了。
driver = webdriver.Edge()

方式三
# 将浏览器driver放到python.exe所在目录,原理同方式二,因为python.exe的目录已经在$PATH中了,之后直接调用
driver = webdirver.Edge()

原理分析

查看模块webdriver,找到类WebDriver的方法__init___(),发现driver的参数为executable_path,并且默认值为msedgedriver.exe。因此如果没有采用方式一的方式调用的话,就会使用默认参数。会根据$PATH变量去查找驱动msedgedriver.exe。如果无法找到就会报未找到driver的错误。但是我使用的selenium版本为3.141.0,发现Edge默认给的驱动是 MicrosoftWebDriver.exe同我下载的driver不同。结果使用方式二和方式三调用。解决方法,直接修改executable_path,将值修改为我下载的驱动msedgedriver.exe即可。

当使用方法一调用时,可选参数executable_path会使用传入的参数代替默认参数。

class WebDriver(RemoteWebDriver):

    def __init__(self, executable_path='msedgedriver.exe',
                 capabilities=None, port=0, verbose=False, service_log_path=None,
                 log_path=None, keep_alive=False):
        # 默认的executable_path='MicrosoftWebDriver.exe'
        """
        Creates a new instance of the chrome driver.

        Starts the service and then creates new instance of chrome driver.

        :Args:
         - executable_path - path to the executable. If the default is used it assumes the executable is in the $PATH
         - capabilities - Dictionary object with non-browser specific
           capabilities only, such as "proxy" or "loggingPref".
         - port - port you would like the service to run, if left as 0, a free port will be found.
         - verbose - whether to set verbose logging in the service
         - service_log_path - Where to log information from the driver.
         - log_path: Deprecated argument for service_log_path
         - keep_alive - Whether to configure ChromeRemoteConnection to use HTTP keep-alive.
         """

 


版权声明:本文为wanglianjun0_0原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。