zoukankan      html  css  js  c++  java
  • selenium源码分析

    import warnings
    
    from selenium.webdriver.remote.webdriver import WebDriver as RemoteWebDriver
    from .remote_connection import ChromeRemoteConnection
    from .service import Service
    from .options import Options
    
    #这个就是入口文件实例化chrome
    class WebDriver(RemoteWebDriver):
        """
        Controls the ChromeDriver and allows you to drive the browser.
    
        You will need to download the ChromeDriver executable from
        http://chromedriver.storage.googleapis.com/index.html
        """
        #入口函数, chromedriver是谷歌浏览器接口,其实就是对谷歌驱动做了一次封装
        #谷歌提供的驱动其实就相当于一个服务器,使用命令就可以调用,而selenium是对驱动做了封装
        #使得编写python脚本就可以调用驱动。类似于postman作用
        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:
             - executable_path - path to the executable. If the default is used it assumes the executable is in the $PATH
             - port - port you would like the service to run, if left as 0, a free port will be found.
             - options - this takes an instance of ChromeOptions
             - service_args - List of args to pass to the driver service
             - desired_capabilities - Dictionary object with non-browser specific
               capabilities only, such as "proxy" or "loggingPref".
             - service_log_path - Where to log information from the driver.
             - chrome_options - Deprecated argument for options
             - keep_alive - Whether to configure ChromeRemoteConnection to use HTTP keep-alive.
            """
            #如果有参数,赋值
            if chrome_options:
                warnings.warn('use options instead of chrome_options',
                              DeprecationWarning, stacklevel=2)
                options = chrome_options
            #如果实例化webdriver没有传参的话,那么给他一个默认值
            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())
            #service_args用来给chromedriver加参数的,比如说一些chromedriver运行日志存放路径
            #获取了一个随机端口并产生一个service实例化
            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
    
        def launch_app(self, id):
            """Launches Chrome app specified by id."""
            return self.execute("launchApp", {'id': id})
    
        def get_network_conditions(self):
            """
            Gets Chrome network emulation settings.
    
            :Returns:
                A dict. For example:
    
                {'latency': 4, 'download_throughput': 2, 'upload_throughput': 2,
                'offline': False}
    
            """
            return self.execute("getNetworkConditions")['value']
    
        def set_network_conditions(self, **network_conditions):
            """
            Sets Chrome network emulation settings.
    
            :Args:
             - network_conditions: A dict with conditions specification.
    
            :Usage:
                driver.set_network_conditions(
                    offline=False,
                    latency=5,  # additional latency (ms)
                    download_throughput=500 * 1024,  # maximal throughput
                    upload_throughput=500 * 1024)  # maximal throughput
    
                Note: 'throughput' can be used to set both (for download and upload).
            """
            self.execute("setNetworkConditions", {
                'network_conditions': network_conditions
            })
    
        def execute_cdp_cmd(self, cmd, cmd_args):
            """
            Execute Chrome Devtools Protocol command and get returned result
    
            The command and command args should follow chrome devtools protocol domains/commands, refer to link
            https://chromedevtools.github.io/devtools-protocol/
    
            :Args:
             - cmd: A str, command name
             - cmd_args: A dict, command args. empty dict {} if there is no command args
    
            :Usage:
                driver.execute_cdp_cmd('Network.getResponseBody', {'requestId': requestId})
    
            :Returns:
                A dict, empty dict {} if there is no result to return.
                For example to getResponseBody:
    
                {'base64Encoded': False, 'body': 'response body string'}
    
            """
            return self.execute("executeCdpCommand", {'cmd': cmd, 'params': cmd_args})['value']
    
        def quit(self):
            """
            Closes the browser and shuts down the ChromeDriver executable
            that is started when starting the ChromeDriver
            """
            try:
                RemoteWebDriver.quit(self)
            except Exception:
                # We don't care about the message because something probably has gone wrong
                pass
            finally:
                self.service.stop()
    
        def create_options(self):
            return Options()

  • 相关阅读:
    hdu 2897 巴什博弈变形
    hdu 2516 FIB博弈模型
    zoj 1904 Beavergnaw 计算圆柱和圆台的体积
    zoj 1806 This Takes the Cake 计算凸四边形和三角形的面积
    zoj 1608 Two Circles and a Rectangle 判断两个圆是否能放入一个矩形中
    zoj 1439 Area Ratio 计算三角形内接圆面积和外接圆面积之比
    zoj 1199 Point of Intersection 求两个圆公切线的交点
    poj 1584 A Round Peg in a Ground Hole 判断多边形是否为凸多边形 + 圆心是否在凸多边形内 + 圆是否在凸多边形内部
    Django-Xadmin
    Django组件-分页器
  • 原文地址:https://www.cnblogs.com/wangxuetest/p/13278139.html
Copyright © 2011-2022 走看看