美文网首页
Selenium源码分析之浏览器参数配置

Selenium源码分析之浏览器参数配置

作者: 假程序员 | 来源:发表于2019-04-05 16:31 被阅读0次

ide:pycharm
language:python
selenium:3.141.0
browser:chrome

WebDriver构造函数源码

class WebDriver(RemoteWebDriver):
    def __init__(self, executable_path="chromedriver", port=0,
                 options=None, service_args=None,
                 desired_capabilities=None, service_log_path=None,
                 chrome_options=None, keep_alive=True):
        """
        Creates a new instance of the chrome driver.

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

        :Args:
         - options - this takes an instance of ChromeOptions
         - desired_capabilities - Dictionary object with non-browser specific
           capabilities only, such as "proxy" or "loggingPref".
         - chrome_options - Deprecated argument for options
        """
        if chrome_options:
            warnings.warn('use options instead of chrome_options',
                          DeprecationWarning, stacklevel=2)
            options = chrome_options

        if options is None:
            # desired_capabilities stays as passed in
            if desired_capabilities is None:
                desired_capabilities = self.create_options().to_capabilities()
        else:
            if desired_capabilities is None:
                desired_capabilities = options.to_capabilities()
            else:
                desired_capabilities.update(options.to_capabilities())

        self.service = Service(
            executable_path,
            port=port,
            service_args=service_args,
            log_path=service_log_path)
        self.service.start()

        try:
            RemoteWebDriver.__init__(
                self,
                command_executor=ChromeRemoteConnection(
                    remote_server_addr=self.service.service_url,
                    keep_alive=keep_alive),
                desired_capabilities=desired_capabilities)
        except Exception:
            self.quit()
            raise
        self._is_remote = False

源码中options参与的部分还不少,但是最终在创建service时所使用的参数是desired_capabilities(dict类型),在上述源码中,首先将非空的chrome_options赋给了options,即chrome_options会覆盖options。根据chrome_options的文档描述,它会弃用options参数,与实际源码一致。
然后对options是否为空进行了分别的处理。
1、当options为None时,如果desired_capabilities为None,则会创建一个默认的浏览器配置信息赋给desired_capabilities;
2、当options不为None时。如果desired_capabilities为空,那么将以options生成浏览器配置信息,并赋给desired_capabilities;如果desired_capabilities不为空,那么将以options更新desired_capabilities中的信息。
到此,desired_capabilities配置信息已完成创建。
下面分析如何创建的desired_capabilities,
self.create_options()是WebDriver的一个实例方法,该方法返回的是Options类的一个实例,进入Options类的构造函数

class Options(object):
    KEY = "goog:chromeOptions"

    def __init__(self):
        self._binary_location = ''
        self._arguments = []
        self._extension_files = []
        self._extensions = []
        self._experimental_options = {}
        self._debugger_address = None
        self._caps = DesiredCapabilities.CHROME.copy()

单从该构造函数中,并不能获得什么特别的信息。
下面查看to_capabilities方法的实现部分。

    def to_capabilities(self):
        """
            Creates a capabilities with all the options that have been set and

            returns a dictionary with everything
        """
        caps = self._caps
        chrome_options = self.experimental_options.copy()
        chrome_options["extensions"] = self.extensions
        if self.binary_location:
            chrome_options["binary"] = self.binary_location
        chrome_options["args"] = self.arguments
        if self.debugger_address:
            chrome_options["debuggerAddress"] = self.debugger_address

        caps[self.KEY] = chrome_options

        return caps

本源码中caps由self._caps赋值,而self._caps在Options的构造函数中被定义,
DesiredCapabilities.CHROME是一个类变量,它实际是一个字典,在本段源码中同时给caps字典增加了一个键值caps[self.KEY] = chrome_options,这样一个desired_capabilities就创建成功了。
到这里对desired_capabilities的创建进行了详细分析,由于python语言限制,options,chrome_options,desired_capabilities并没有被标志其类型。下面列出其类型,方便大家使用:
options:from selenium.webdriver.chrome.options import Options
chrome_options:from selenium.webdriver.chrome.options import Options
desired_capabilities:dictionary

下面列出两种创建配置的方式供大家使用:

一:

    DesiredCap = DesiredCapabilities.CHROME.copy()
    chrome_options = dict()
    chrome_options["args"] = list()
    chrome_options["args"].append("--incognito") #隐身
    chrome_options["args"].append("--headless") #无界面
    DesiredCap["goog:chromeOptions"] = chrome_options
    path = "/Users/apple/Seleniumdriver/chromedriver"
    driver = WebDriver(executable_path=path, desired_capabilities=DesiredCap, service_log_path="log.txt")

log.txt包含如下内容,进一步证明以上面所展示的方式能够有效配置谷歌浏览器的启动参数。

[1554741051.625][INFO]: [5f2f1a37a6483988d9a6ecb38679038e] COMMAND InitSession {
   "capabilities": {
      "alwaysMatch": {
         "browserName": "chrome",
         "goog:chromeOptions": {
            "args": [ "--incognito", "--headless" ]
         },
         "platformName": "any"
      },
      "firstMatch": [ {

      } ]
   },
   "desiredCapabilities": {
      "browserName": "chrome",
      "goog:chromeOptions": {
         "args": [ "--incognito", "--headless" ]
      },
      "platform": "ANY",
      "version": ""
   }
}
[1554741051.629][INFO]: Launching chrome: /Applications/Google Chrome.app/Contents/MacOS/Google Chrome --disable-background-networking --disable-client-side-phishing-detection --disable-default-apps --disable-hang-monitor --disable-popup-blocking --disable-prompt-on-repost --disable-sync --disable-web-resources --enable-automation --enable-blink-features=ShadowDOMV0 --enable-logging --force-fieldtrials=SiteIsolationExtensions/Control --headless --ignore-certificate-errors --incognito --load-extension=/var/folders/nt/33z_3wbj0x76ckgm5dvh7x2m0000gn/T/.com.google.Chrome.v8Pzac/internal --log-level=0 --metrics-recording-only --no-first-run --password-store=basic --remote-debugging-port=0 --test-type=webdriver --use-mock-keychain --user-data-dir=/var/folders/nt/33z_3wbj0x76ckgm5dvh7x2m0000gn/T/.com.google.Chrome.kXTL9R data:,

二:

    options = Options()
    options.add_argument("--incognito")
    options.add_argument("--headless")
    path = "/Users/apple/Seleniumdriver/chromedriver"
    driver = WebDriver(executable_path=path, options=options,
                       service_log_path="log.txt")
    driver.get("https://www.baidu.com")
    driver.close()
    driver.quit()

log.txt包含如下内容,进一步证明以上面所展示的方式能够有效配置谷歌浏览器的启动参数。

[1554741483.643][INFO]: [c0a50b90c90a79ceb2047548dc4d3fd9] COMMAND InitSession {
   "capabilities": {
      "alwaysMatch": {
         "browserName": "chrome",
         "goog:chromeOptions": {
            "args": [ "--incognito", "--headless" ],
            "extensions": [  ]
         },
         "platformName": "any"
      },
      "firstMatch": [ {

      } ]
   },
   "desiredCapabilities": {
      "browserName": "chrome",
      "goog:chromeOptions": {
         "args": [ "--incognito", "--headless" ],
         "extensions": [  ]
      },
      "platform": "ANY",
      "version": ""
   }
}
[1554741483.647][INFO]: Launching chrome: /Applications/Google Chrome.app/Contents/MacOS/Google Chrome --disable-background-networking --disable-client-side-phishing-detection --disable-default-apps --disable-hang-monitor --disable-popup-blocking --disable-prompt-on-repost --disable-sync --disable-web-resources --enable-automation --enable-blink-features=ShadowDOMV0 --enable-logging --force-fieldtrials=SiteIsolationExtensions/Control --headless --ignore-certificate-errors --incognito --load-extension=/var/folders/nt/33z_3wbj0x76ckgm5dvh7x2m0000gn/T/.com.google.Chrome.vw3b9S/internal --log-level=0 --metrics-recording-only --no-first-run --password-store=basic --remote-debugging-port=0 --test-type=webdriver --use-mock-keychain --user-data-dir=/var/folders/nt/33z_3wbj0x76ckgm5dvh7x2m0000gn/T/.com.google.Chrome.er2pVN data:,

相关文章

网友评论

      本文标题:Selenium源码分析之浏览器参数配置

      本文链接:https://www.haomeiwen.com/subject/bqfkiqtx.html