o
    Vh                     @   s>  d Z ddlZddlZddlZddlZddlZddlZddlZddlZddl	Z	ddl
mZ ddlmZ ddlmZ ddlmZ ddlmZ ddlmZ dd	lmZ dd
lmZ ddlmZ ddlmZ ddlmZ ddlmZ ddlmZ ddlmZ ddlmZ ddlmZ ddlmZ ddl m!Z! ddl"m#Z# ddl$m%Z% ddl$m&Z& ddl$m'Z' ddl(m)Z) ddl*m+Z+ ddl,m-Z- ddl.m/Z/ ddl0m1Z1 ddl0m2Z2 dd l3m4Z4 dd!l5m6Z6 dd"l7m8Z8 dd#l9m:Z: dd$l;m<Z< dd%l=m>Z> da?d&d' Z@d(d) ZAd6d+d,ZBd-ee d.efd/d0ZCG d1d2 d2ed3ZDG d4d5 d5eDZEdS )7zThe WebDriver implementation.    N)ABCMeta)	b64decode)urlsafe_b64encode)asynccontextmanager)contextmanager)import_module)Dict)List)Optional)Union)InvalidArgumentException)JavascriptException)NoSuchCookieException)NoSuchElementException)WebDriverException)By)BaseOptions)PrintOptions)Timeouts)
Credential)VirtualAuthenticatorOptions)required_virtual_authenticator)
RelativeBy   )BidiConnection)Command)ErrorHandler)FileDetector)LocalFileDetector)Mobile)RemoteConnection)	ScriptKey)
ShadowRoot)SwitchTo)
WebElementc                   C   s   t stda d S d S )Nz"selenium.webdriver.common.bidi.cdp)cdpr    r&   r&   `/home/air/yokohama/back/venv/lib/python3.10/site-packages/selenium/webdriver/remote/webdriver.py
import_cdpE   s   r(   c                 C   s8   t | } i }|  D ]\}}|||< qdi g|diS )a  Makes a W3C alwaysMatch capabilities object.

    Filters out capability names that are not in the W3C spec. Spec-compliant
    drivers will reject requests containing unknown capability names.

    Moves the Firefox profile, if present, from the old location to the new Firefox
    options object.

    :Args:
     - caps - A dictionary of capabilities requested by the caller.
    capabilities)
firstMatchalwaysMatch)copydeepcopyitems)capsalways_matchkvr&   r&   r'   _create_capsK   s
   

r3   Fc           
         sb   ddl m} ddlm} ddlm} ddlm} ||||g}t fdd|D t	}	|	|||dS )	Nr   )ChromeRemoteConnection)EdgeRemoteConnection)FirefoxRemoteConnection)SafariRemoteConnectionc                 3   s$    | ]}|j  d kr|V  qdS )browserNameN)browser_nameget).0cr)   r&   r'   	<genexpr>e   s   " z(get_remote_connection.<locals>.<genexpr>)
keep_aliveignore_proxy)
+selenium.webdriver.chrome.remote_connectionr4   )selenium.webdriver.edge.remote_connectionr5   ,selenium.webdriver.firefox.remote_connectionr6   +selenium.webdriver.safari.remote_connectionr7   nextr    )
r)   command_executorr?   ignore_local_proxyr4   r5   r6   r7   
candidateshandlerr&   r=   r'   get_remote_connection^   s   rJ   optionsreturnc                 C   s   di i}g }| D ]	}| |  qt|}i }t|D ]8}|}|d |k rT||  }|D ]%}	|	||d   v rS|| |	 ||d  |	 krS||	|| |	 i q.qi }
| D ]\}}||
|< q[|D ]
}|
D ]}||= qjqf|
|d d< ||d d< |S )Nr)   r   r+   r*   )appendto_capabilitieslenrangekeysupdater.   )rK   r)   optsopt	opts_sizesamesiesi	min_index
first_keyskysalwaysr1   r2   r&   r&   r'   create_matchesj   s2   
r\   c                   @   s   e Zd ZdZdS )BaseWebDriverzAbstract Base Class for all Webdriver subtypes.

    ABC's allow custom implementations of Webdriver to be registered so
    that isinstance type checks will succeed.
    N)__name__
__module____qualname____doc__r&   r&   r&   r'   r]      s    r]   )	metaclassc                   @   s  e Zd ZdZeZeZ				ddee	e
e	 f ddfddZd	d
 Zdd Zdejeje  deje dejej fddZedd ZedefddZedefddZdd Zdd ZdeddfddZdd  Z d!edefd"d#Z!d$d% Z"dd&ed'edefd(d)Z#d*eddfd+d,Z$edefd-d.Z%dd/ede&fd0d1Z'd2e&ddfd3d4Z(de
e fd5d6Z)d7d8 Z*d/efd9d:Z+edefd;d<Z,edefd=d>Z-dd?d@Z.ddAdBZ/edefdCdDZ0ede
e fdEdFZ1ddGdHZ2ddIdJZ3ddKdLZ4ddMee5 defdNdOZ6ede7fdPdQZ8ddRdSZ9ddTdUZ:ddVdWZ;de
e fdXdYZ<dejej= fdZd[Z>dd\d]Z?dd^d_Z@dd`daZAdbeBddfdcddZCdbeBddfdedfZDdbeBddfdgdhZEedeFfdidjZGeGjHddkdjZGeIjJdfdlee defdmdnZKeIjJdfdlee de
e fdodpZLedefdqdrZMdeNfdsdtZOdeNfdudvZPdeQfdwdxZRdefdydzZSdd|eddfd}d~ZTdd|edefddZUdd|edefddZVddefddZWd|eddfddZXdefddZYddefddZZede[fddZ\e\jHdddZ\edd Z]e]jHdddZ]edd Z^dd Z_e`dd Zadd ZbdecddfddZdedefddZeefdddZgefdehddfddZiefde
eh fddZjefdeeekf ddfddZlefdddZmefdeNddfddZndefddZodededdfddZpdddZqdS )	WebDrivera  Controls a browser by sending commands to a remote server. This server
    is expected to be running the WebDriver wire protocol as defined at
    https://www.selenium.dev/documentation/legacy/json_wire_protocol/.

    :Attributes:
     - session_id - String ID of the browser session started and controlled by this WebDriver.
     - capabilities - Dictionary of effective capabilities of this browser session as returned
         by the remote server. See https://www.selenium.dev/documentation/legacy/desired_capabilities/
     - command_executor - remote_connection.RemoteConnection object used to execute commands.
     - error_handler - errorhandler.ErrorHandler object used to handle errors.
    http://127.0.0.1:4444TNrK   rL   c                 C   s   t |trt|}d}n| }|j}|| _t | jttfr't||||d| _d| _	d| _
i | _i | _t | _t| | _t| | _|pEt | _d| _|   | | dS )a  Create a new driver that will issue commands using the wire
        protocol.

        :Args:
         - command_executor - Either a string representing URL of the remote server or a custom
             remote_connection.RemoteConnection object. Defaults to 'http://127.0.0.1:4444/wd/hub'.
         - keep_alive - Whether to configure remote_connection.RemoteConnection to use
             HTTP keep-alive. Defaults to True.
         - file_detector - Pass custom file detector object during instantiation. If None,
             then default LocalFileDetector() will be used.
         - options - instance of a driver options.Options class
        F)rF   r?   rG   TN)
isinstancelistr\   rN   _ignore_local_proxyrF   strbytesrJ   
_is_remote
session_idr/   pinned_scriptsr   error_handlerr#   
_switch_tor   _mobiler   file_detector_authenticator_idstart_clientstart_session)selfrF   r?   rp   rK   r)   rg   r&   r&   r'   __init__   s0   


zWebDriver.__init__c                 C   s&   dt | j dt | j d| j dS )N<.z (session="z")>)typer_   r^   rk   rt   r&   r&   r'   __repr__   s   &zWebDriver.__repr__c                 C   s   | S Nr&   ry   r&   r&   r'   	__enter__   s   zWebDriver.__enter__exc_typeexc	tracebackc                 C   s   |    d S r{   )quit)rt   r}   r~   r   r&   r&   r'   __exit__   s   zWebDriver.__exit__c                 o   sP    d}t | j|s| j}||i || _zdV  W |r || _dS dS |r'|| _w )a  Overrides the current file detector (if necessary) in limited
        context. Ensures the original file detector is set afterwards.

        Example::

            with webdriver.file_detector_context(UselessFileDetector):
                someinput.send_keys('/etc/hosts')

        :Args:
         - file_detector_class - Class of the desired file detector. If the class is different
             from the current file_detector, then the class is instantiated with args and kwargs
             and used as a file detector during the duration of the context manager.
         - args - Optional arguments that get passed to the file detector class during
             instantiation.
         - kwargs - Keyword arguments, passed the same way as args.
        N)re   rp   )rt   file_detector_classargskwargslast_detectorr&   r&   r'   file_detector_context   s   
zWebDriver.file_detector_contextc                 C      | j S r{   )ro   ry   r&   r&   r'   mobile      zWebDriver.mobilec                 C   s   d| j v r
| j d S td)zReturns the name of the underlying browser for this instance.

        :Usage:
            ::

                name = driver.name
        r8   z1browserName not specified in session capabilities)r/   KeyErrorry   r&   r&   r'   name   s   
	
zWebDriver.namec                 C      dS )zxCalled before starting a new session.

        This method may be overridden to define custom startup behavior.
        Nr&   ry   r&   r&   r'   rr     s   zWebDriver.start_clientc                 C   r   )zCalled after executing a quit command.

        This method may be overridden to define custom shutdown
        behavior.
        Nr&   ry   r&   r&   r'   stop_client  s   zWebDriver.stop_clientr)   c                 C   s6   t |}| tj|d }|d| _|d| _dS )zCreates a new session with the desired capabilities.

        :Args:
         - capabilities - a capabilities dict to start the session with.
        value	sessionIdr)   N)r3   executer   NEW_SESSIONr:   rk   r/   )rt   r)   r/   responser&   r&   r'   rs     s   zWebDriver.start_sessionc                    s   t |tri }| D ]\}} |||< q|S t | jr$d|jiS t | jr/d|jiS t |tr?t fdd|D S |S )N#element-6066-11e4-a52e-4f735466cecf"shadow-6066-11e4-a52e-4f735466cecfc                 3       | ]}  |V  qd S r{   )_wrap_valuer;   itemry   r&   r'   r>   3      z(WebDriver._wrap_value.<locals>.<genexpr>)re   dictr.   r   _web_element_clsid_shadowroot_clsrf   )rt   r   	convertedkeyvalr&   ry   r'   r   (  s   



zWebDriver._wrap_value
element_idc                 C   s   |  | |S )z6Creates a web element with the specified `element_id`.)r   )rt   r   r&   r&   r'   create_web_element6  s   zWebDriver.create_web_elementc                    s   t |tr.d|v r |d S d|v r  |d S | D ]\}} |||< q |S t |tr>t fdd|D S |S )Nr   r   c                 3   r   r{   )_unwrap_valuer   ry   r&   r'   r>   D  r   z*WebDriver._unwrap_value.<locals>.<genexpr>)re   r   r   r   r.   r   rf   )rt   r   r   r   r&   ry   r'   r   :  s   

zWebDriver._unwrap_valuedriver_commandparamsc                 C   sx   |  |}| jr|sd| ji}n	d|vr| j|d< | j||}|r5| j| | |dd|d< |S dd| jdS )aH  Sends a command to be executed by a command.CommandExecutor.

        :Args:
         - driver_command: The name of the command to execute as a string.
         - params: A dictionary of named parameters to send with the command.

        :Returns:
          The command's JSON response loaded into a dictionary object.
        r   r   Nr   )successr   r   )r   rk   rF   r   rm   check_responser   r:   )rt   r   r   r   r&   r&   r'   r   G  s   


zWebDriver.executeurlc                 C      |  tjd|i dS )z0Loads a web page in the current browser session.r   N)r   r   GET)rt   r   r&   r&   r'   r:   b  s   zWebDriver.getc                 C   s   |  tjddS )zuReturns the title of the current page.

        :Usage:
            ::

                title = driver.title
        r    )r   r   	GET_TITLEr:   ry   r&   r&   r'   titlef  s   	zWebDriver.titlescriptc                 C   s   t |}|| j|j< |S )zUStore common javascript scripts to be executed later by a unique
        hashable ID.)r!   rl   r   )rt   r   
script_keyscript_key_instancer&   r&   r'   
pin_scriptq  s   zWebDriver.pin_scriptr   c                 C   s<   z
| j |j W dS  ty   td| d| j  dw )z$Remove a pinned script from storage.zNo script with key: z existed in N)rl   popr   r   )rt   r   r&   r&   r'   unpinx  s
   zWebDriver.unpinc                 C   s
   t | jS r{   )rf   rl   ry   r&   r&   r'   get_pinned_scripts  s   
zWebDriver.get_pinned_scriptsc                 G   sV   t |trz| j|j }W n ty   tdw t|}tj}| 	|||dd S )a'  Synchronously Executes JavaScript in the current window/frame.

        :Args:
         - script: The JavaScript to execute.
         - \*args: Any applicable arguments for your JavaScript.

        :Usage:
            ::

                driver.execute_script('return document.title;')
        z Pinned script could not be foundr   r   r   )
re   r!   rl   r   r   r   rf   r   W3C_EXECUTE_SCRIPTr   rt   r   r   converted_argscommandr&   r&   r'   execute_script  s   
zWebDriver.execute_scriptc                 G   s$   t |}tj}| |||dd S )a  Asynchronously Executes JavaScript in the current window/frame.

        :Args:
         - script: The JavaScript to execute.
         - \*args: Any applicable arguments for your JavaScript.

        :Usage:
            ::

                script = "var callback = arguments[arguments.length - 1]; " \
                         "window.setTimeout(function(){ callback('timeout') }, 3000);"
                driver.execute_async_script(script)
        r   r   )rf   r   W3C_EXECUTE_SCRIPT_ASYNCr   r   r&   r&   r'   execute_async_script  s   zWebDriver.execute_async_scriptc                 C      |  tjd S )znGets the URL of the current page.

        :Usage:
            ::

                driver.current_url
        r   )r   r   GET_CURRENT_URLry   r&   r&   r'   current_url     	zWebDriver.current_urlc                 C   r   )zqGets the source of the current page.

        :Usage:
            ::

                driver.page_source
        r   )r   r   GET_PAGE_SOURCEry   r&   r&   r'   page_source  r   zWebDriver.page_sourcec                 C      |  tj dS )zcCloses the current window.

        :Usage:
            ::

                driver.close()
        N)r   r   CLOSEry   r&   r&   r'   close     zWebDriver.closec                 C   s:   z|  tj W |   | j  dS |   | j  w )z|Quits the driver and closes every associated window.

        :Usage:
            ::

                driver.quit()
        N)r   r   QUITr   rF   r   ry   r&   r&   r'   r     s   zWebDriver.quitc                 C   r   )zReturns the handle of the current window.

        :Usage:
            ::

                driver.current_window_handle
        r   )r   r   W3C_GET_CURRENT_WINDOW_HANDLEry   r&   r&   r'   current_window_handle  r   zWebDriver.current_window_handlec                 C   r   )zReturns the handles of all windows within the current session.

        :Usage:
            ::

                driver.window_handles
        r   )r   r   W3C_GET_WINDOW_HANDLESry   r&   r&   r'   window_handles  r   zWebDriver.window_handlesc                 C   s   t j}| |d dS )z5Maximizes the current window that webdriver is using.N)r   W3C_MAXIMIZE_WINDOWr   )rt   r   r&   r&   r'   maximize_window  s   zWebDriver.maximize_windowc                 C   r   )z<Invokes the window manager-specific 'full screen' operation.N)r   r   FULLSCREEN_WINDOWry   r&   r&   r'   fullscreen_window     zWebDriver.fullscreen_windowc                 C   r   )z9Invokes the window manager-specific 'minimize' operation.N)r   r   MINIMIZE_WINDOWry   r&   r&   r'   minimize_window  r   zWebDriver.minimize_windowprint_optionsc                 C   s"   i }|r|  }| tj|d S )zTakes PDF of the current page.

        The driver makes a best effort to return a PDF based on the
        provided parameters.
        r   )to_dictr   r   
PRINT_PAGE)rt   r   rK   r&   r&   r'   
print_page  s   zWebDriver.print_pagec                 C   r   )a<  
        :Returns:
            - SwitchTo: an object containing all options to switch focus into

        :Usage:
            ::

                element = driver.switch_to.active_element
                alert = driver.switch_to.alert
                driver.switch_to.default_content()
                driver.switch_to.frame('frame_name')
                driver.switch_to.frame(1)
                driver.switch_to.frame(driver.find_elements(By.TAG_NAME, "iframe")[0])
                driver.switch_to.parent_frame()
                driver.switch_to.window('main')
        )rn   ry   r&   r&   r'   	switch_to	  s   zWebDriver.switch_toc                 C   r   )zvGoes one step backward in the browser history.

        :Usage:
            ::

                driver.back()
        N)r   r   GO_BACKry   r&   r&   r'   back  r   zWebDriver.backc                 C   r   )zxGoes one step forward in the browser history.

        :Usage:
            ::

                driver.forward()
        N)r   r   
GO_FORWARDry   r&   r&   r'   forward(  r   zWebDriver.forwardc                 C   r   )zfRefreshes the current page.

        :Usage:
            ::

                driver.refresh()
        N)r   r   REFRESHry   r&   r&   r'   refresh2  r   zWebDriver.refreshc                 C   r   )zReturns a set of dictionaries, corresponding to cookies visible in
        the current session.

        :Usage:
            ::

                driver.get_cookies()
        r   )r   r   GET_ALL_COOKIESry   r&   r&   r'   get_cookies=  r   zWebDriver.get_cookiesc                 C   sD   t t | tjd|id W  d   S 1 sw   Y  dS )zGet a single cookie by name. Returns the cookie if found, None if
        not.

        :Usage:
            ::

                driver.get_cookie('my_cookie')
        r   r   N)
contextlibsuppressr   r   r   
GET_COOKIErt   r   r&   r&   r'   
get_cookieH  s   	 zWebDriver.get_cookiec                 C   r   )zDeletes a single cookie with the given name.

        :Usage:
            ::

                driver.delete_cookie('my_cookie')
        r   N)r   r   DELETE_COOKIEr   r&   r&   r'   delete_cookieU  s   zWebDriver.delete_cookiec                 C   r   )zDelete all cookies in the scope of the session.

        :Usage:
            ::

                driver.delete_all_cookies()
        N)r   r   DELETE_ALL_COOKIESry   r&   r&   r'   delete_all_cookies_  r   zWebDriver.delete_all_cookiesc                 C   sD   d|v r|d dv sJ |  tjd|i dS |  tjd|i dS )ag  Adds a cookie to your current session.

        :Args:
         - cookie_dict: A dictionary object, with required keys - "name" and "value";
            optional keys - "path", "domain", "secure", "httpOnly", "expiry", "sameSite"

        :Usage:
            ::

                driver.add_cookie({'name' : 'foo', 'value' : 'bar'})
                driver.add_cookie({'name' : 'foo', 'value' : 'bar', 'path' : '/'})
                driver.add_cookie({'name' : 'foo', 'value' : 'bar', 'path' : '/', 'secure' : True})
                driver.add_cookie({'name' : 'foo', 'value' : 'bar', 'sameSite' : 'Strict'})
        sameSite)StrictLaxNonecookieN)r   r   
ADD_COOKIE)rt   cookie_dictr&   r&   r'   
add_cookiei  s   zWebDriver.add_cookietime_to_waitc                 C   "   |  tjdtt|d i dS )a  Sets a sticky timeout to implicitly wait for an element to be found,
        or a command to complete. This method only needs to be called one time
        per session. To set the timeout for calls to execute_async_script, see
        set_script_timeout.

        :Args:
         - time_to_wait: Amount of time to wait (in seconds)

        :Usage:
            ::

                driver.implicitly_wait(30)
        implicit  Nr   r   SET_TIMEOUTSintfloatrt   r   r&   r&   r'   implicitly_wait  s   "zWebDriver.implicitly_waitc                 C   r   )a!  Set the amount of time that the script should wait during an
        execute_async_script call before throwing an error.

        :Args:
         - time_to_wait: The amount of time to wait (in seconds)

        :Usage:
            ::

                driver.set_script_timeout(30)
        r   r   Nr   r   r&   r&   r'   set_script_timeout  s   "zWebDriver.set_script_timeoutc              	   C   sV   z|  tjdtt|d i W dS  ty*   |  tjt|d dd Y dS w )zSet the amount of time to wait for a page load to complete before
        throwing an error.

        :Args:
         - time_to_wait: The amount of time to wait

        :Usage:
            ::

                driver.set_page_load_timeout(30)
        pageLoadr   z	page load)msrx   N)r   r   r   r   r   r   r   r&   r&   r'   set_page_load_timeout  s
   $"zWebDriver.set_page_load_timeoutc                 C   sT   |  tjd }|dd |d< |dd |d< |dd |d< td	i |S )
zGet all the timeouts that have been set on the current session.

        :Usage:
            ::

                driver.timeouts
        :rtype: Timeout
        r   r   r   implicit_waitr   	page_loadr   Nr&   )r   r   GET_TIMEOUTSr   r   )rt   timeoutsr&   r&   r'   r    s
   
zWebDriver.timeoutsc                 C   s   |  tj| d }dS )a  Set all timeouts for the session. This will override any previously
        set timeouts.

        :Usage:
            ::
                my_timeouts = Timeouts()
                my_timeouts.implicit_wait = 10
                driver.timeouts = my_timeouts
        r   N)r   r   r   _to_json)rt   r  _r&   r&   r'   r    s   r   c                 C   s   t |tr| j||d}|std|j |d S |tjkr)tj}d| d}n|tjkr7tj}d| }n|tj	krEtj}d| d}| 
tj||dd	 S )
zFind an element given a By strategy and locator.

        :Usage:
            ::

                element = driver.find_element(By.ID, 'foo')

        :rtype: WebElement
        )byr   z%Cannot locate relative element with: r   [id=""]rw   [name="usingr   r   )re   r   find_elementsr   rootr   IDCSS_SELECTOR
CLASS_NAMENAMEr   r   FIND_ELEMENT)rt   r  r   elementsr&   r&   r'   find_element  s   




zWebDriver.find_elementc                 C   s   t |tr(dtddd }t|dd}d| d}| ||	 S |t
jkr7t
j}d| d	}n|t
jkrEt
j}d| }n|t
jkrSt
j}d
| d	}| tj||dd p`g S )zFind elements given a By strategy and locator.

        :Usage:
            ::

                elements = driver.find_elements(By.CLASS_NAME, 'foo')

        :rtype: list of WebElement
        rw   NzfindElements.jsutf8z/* findElements */return (z).apply(null, arguments);r  r  r  r	  r   )re   r   joinr^   splitpkgutilget_datadecoder   r   r   r  r  r  r  r   r   FIND_ELEMENTS)rt   r  r   _pkgraw_functionfind_element_jsr&   r&   r'   r    s   




zWebDriver.find_elementsc                 C   r   )z4Returns the drivers current capabilities being used.)r/   ry   r&   r&   r'   r)        zWebDriver.capabilitiesc                 C   s   t | dstjdtdd |  }z1z$t|d}|| W d   n1 s,w   Y  W W ~dS W W ~dS  t	yF   Y W ~dS w ~w )	a  Saves a screenshot of the current window to a PNG image file.
        Returns False if there is any IOError, else returns True. Use full
        paths in your filename.

        :Args:
         - filename: The full path you wish to save your screenshot to. This
           should end with a `.png` extension.

        :Usage:
            ::

                driver.get_screenshot_as_file('/Screenshots/foo.png')
        z.pngz^name used for saved screenshot does not match file type. It should end with a `.png` extension   
stacklevelwbNFT)
rh   lowerendswithwarningswarnUserWarningget_screenshot_as_pngopenwriteOSError)rt   filenamepngfr&   r&   r'   get_screenshot_as_file
  s*    z WebDriver.get_screenshot_as_filec                 C   s
   |  |S )a  Saves a screenshot of the current window to a PNG image file.
        Returns False if there is any IOError, else returns True. Use full
        paths in your filename.

        :Args:
         - filename: The full path you wish to save your screenshot to. This
           should end with a `.png` extension.

        :Usage:
            ::

                driver.save_screenshot('/Screenshots/foo.png')
        )r0  )rt   r-  r&   r&   r'   save_screenshot(  s   
zWebDriver.save_screenshotc                 C   s   t |  dS )zGets the screenshot of the current window as a binary data.

        :Usage:
            ::

                driver.get_screenshot_as_png()
        ascii)r   get_screenshot_as_base64encodery   r&   r&   r'   r)  8  s   zWebDriver.get_screenshot_as_pngc                 C   r   )zGets the screenshot of the current window as a base64 encoded string
        which is useful in embedded images in HTML.

        :Usage:
            ::

                driver.get_screenshot_as_base64()
        r   )r   r   
SCREENSHOTry   r&   r&   r'   r3  B  r   z"WebDriver.get_screenshot_as_base64currentwindowHandlec                 C   s$   |  | | jt|t|d dS )a$  Sets the width and height of the current window. (window.resizeTo)

        :Args:
         - width: the width in pixels to set the window to
         - height: the height in pixels to set the window to

        :Usage:
            ::

                driver.set_window_size(800,600)
        widthheightN"_check_if_window_handle_is_currentset_window_rectr   )rt   r9  r:  r7  r&   r&   r'   set_window_sizeM  s   
zWebDriver.set_window_sizec                    s8   |  | |    ddr d   fdddD S )zGets the width and height of the current window.

        :Usage:
            ::

                driver.get_window_size()
        r   Nc                       i | ]}| | qS r&   r&   r;   r1   sizer&   r'   
<dictcomp>k      z-WebDriver.get_window_size.<locals>.<dictcomp>r8  )r<  get_window_rectr:   rt   r7  r&   rA  r'   get_window_size\  s
   
	zWebDriver.get_window_sizec                 C   s    |  | | jt|t|dS )a.  Sets the x,y position of the current window. (window.moveTo)

        :Args:
         - x: the x-coordinate in pixels to set the window position
         - y: the y-coordinate in pixels to set the window position

        :Usage:
            ::

                driver.set_window_position(0,0)
        xyr;  )rt   rI  rJ  r7  r&   r&   r'   set_window_positionm  s   
zWebDriver.set_window_positionc                    s$   |  | |    fdddD S )zGets the x,y position of the current window.

        :Usage:
            ::

                driver.get_window_position()
        c                    r?  r&   r&   r@  positionr&   r'   rC    rD  z1WebDriver.get_window_position.<locals>.<dictcomp>rH  )r<  rE  rF  r&   rL  r'   get_window_position|  s   
	zWebDriver.get_window_positionc                 C   s   |dkrt jddd dS dS )z5Warns if the window handle is not equal to `current`.r6  z?Only 'current' window is supported for W3C compatible browsers.r   r!  N)r&  r'  rF  r&   r&   r'   r<    s   z,WebDriver._check_if_window_handle_is_currentc                 C   r   )zGets the x, y coordinates of the window as well as height and width
        of the current window.

        :Usage:
            ::

                driver.get_window_rect()
        r   )r   r   GET_WINDOW_RECTry   r&   r&   r'   rE    r   zWebDriver.get_window_rectc                 C   s<   |du r|du r|s|st d| tj||||dd S )a  Sets the x, y coordinates of the window as well as height and width
        of the current window. This method is only supported for W3C compatible
        browsers; other browsers should use `set_window_position` and
        `set_window_size`.

        :Usage:
            ::

                driver.set_window_rect(x=10, y=10)
                driver.set_window_rect(width=100, height=200)
                driver.set_window_rect(x=10, y=10, width=100, height=200)
        Nz'x and y or height and width need values)rI  rJ  r9  r:  r   )r   r   r   SET_WINDOW_RECT)rt   rI  rJ  r9  r:  r&   r&   r'   r=    s   zWebDriver.set_window_rectc                 C   r   r{   )_file_detectorry   r&   r&   r'   rp     r   zWebDriver.file_detectorc                 C   s(   |st dt|tst d|| _dS )a0  Set the file detector to be used when sending keyboard input. By
        default, this is set to a file detector that does nothing.

        see FileDetector
        see LocalFileDetector
        see UselessFileDetector

        :Args:
         - detector: The detector to use. Must not be None.
        z,You may not set a file detector that is nullz+Detector has to be instance of FileDetectorN)r   re   r   rQ  )rt   detectorr&   r&   r'   rp     s
   

c                 C   r   )zGets the current orientation of the device.

        :Usage:
            ::

                orientation = driver.orientation
        r   )r   r   GET_SCREEN_ORIENTATIONry   r&   r&   r'   orientation  r   zWebDriver.orientationc                 C   s2   ddg}|  |v r| tjd|i dS td)zSets the current orientation of the device.

        :Args:
         - value: orientation to set it to.

        :Usage:
            ::

                driver.orientation = 'landscape'
        	LANDSCAPEPORTRAITrT  z>You can only set the orientation to 'LANDSCAPE' and 'PORTRAIT'N)upperr   r   SET_SCREEN_ORIENTATIONr   )rt   r   allowed_valuesr&   r&   r'   rT    s   c                 C   r   )zGets a list of the available log types. This only works with w3c
        compliant browsers.

        :Usage:
            ::

                driver.log_types
        r   )r   r   GET_AVAILABLE_LOG_TYPESry   r&   r&   r'   	log_types  s   
zWebDriver.log_typesc                 C   s   |  tjd|id S )a>  Gets the log for a given log type.

        :Args:
         - log_type: type of log that which will be returned

        :Usage:
            ::

                driver.get_log('browser')
                driver.get_log('driver')
                driver.get_log('client')
                driver.get_log('server')
        rx   r   )r   r   GET_LOG)rt   log_typer&   r&   r'   get_log  s   zWebDriver.get_logc              
   C  s
  t   | jdr| jd}| jddd }n|  \}}|s(tdt|}t|4 I d H B}|	|j
 I d H }|d j}||4 I d H }t|t|V  W d   I d H  n1 I d H shw   Y  W d   I d H  d S 1 I d H s~w   Y  d S )Nzse:cdpzse:cdpVersionrw   r   z2Unable to find url to connect to from capabilities)r(   r/   r:   r  _get_cdp_detailsr   r%   import_devtoolsopen_cdpr   targetget_targets	target_idopen_sessionr   )rt   ws_urlversiondevtoolsconntargetsrd  sessionr&   r&   r'   bidi_connection  s    

*.zWebDriver.bidi_connectionc                 C   s   dd l }dd l}| }d}| jddkr | jdd}n| jddkr2| jdd}nd	}| jd
}|dd| d}||j}|d}|d}	dd l}
|r`d}||	fS |
	d|
d}||	fS )Nr   Fr8   chromezgoog:chromeOptionsdebuggerAddressmsedgezms:edgeOptionsTzmoz:debuggerAddressr   zhttp://z/json/versionBrowserwebSocketDebuggerUrlU   z
.*/(\d+)\.r   )jsonurllib3PoolManagerr/   r:   requestloadsdataresearchgroup)rt   rs  rt  http_firefoxdebugger_addressresrx  browser_versionwebsocket_urlry  rg  r&   r&   r'   r_    s(   

zWebDriver._get_cdp_detailsc                 C   s   |  tj| d | _dS )z4Adds a virtual authenticator with the given options.r   N)r   r   ADD_VIRTUAL_AUTHENTICATORr   rq   )rt   rK   r&   r&   r'   add_virtual_authenticator0  s   z#WebDriver.add_virtual_authenticatorc                 C   r   )z,Returns the id of the virtual authenticator.)rq   ry   r&   r&   r'   virtual_authenticator_id4  r  z"WebDriver.virtual_authenticator_idc                 C   s   |  tjd| ji d| _dS )zRemoves a previously added virtual authenticator.

        The authenticator is no longer valid after removal, so no
        methods may be called.
        authenticatorIdN)r   r   REMOVE_VIRTUAL_AUTHENTICATORrq   ry   r&   r&   r'   remove_virtual_authenticator9  s   
z&WebDriver.remove_virtual_authenticator
credentialc                 C   s$   |  tji | d| ji dS )z,Injects a credential into the authenticator.r  N)r   r   ADD_CREDENTIALr   rq   )rt   r  r&   r&   r'   add_credentialC  s   $zWebDriver.add_credentialc                 C   s&   |  tjd| ji}dd |d D S )z;Returns the list of credentials owned by the authenticator.r  c                 S   s   g | ]}t |qS r&   )r   	from_dict)r;   r  r&   r&   r'   
<listcomp>L  rD  z-WebDriver.get_credentials.<locals>.<listcomp>r   )r   r   GET_CREDENTIALSrq   )rt   credential_datar&   r&   r'   get_credentialsH  s   zWebDriver.get_credentialscredential_idc                 C   s0   t |trt| }| tj|| jd dS )z,Removes a credential from the authenticator.)credentialIdr  N)re   	bytearrayr   r  r   r   REMOVE_CREDENTIALrq   )rt   r  r&   r&   r'   remove_credentialN  s
   
zWebDriver.remove_credentialc                 C   s   |  tjd| ji dS )z/Removes all credentials from the authenticator.r  N)r   r   REMOVE_ALL_CREDENTIALSrq   ry   r&   r&   r'   remove_all_credentialsY  s   z WebDriver.remove_all_credentialsverifiedc                 C   s   |  tj| j|d dS )zSets whether the authenticator will simulate success or fail on user
        verification.

        verified: True if the authenticator will pass user verification, False otherwise.
        )r  isUserVerifiedN)r   r   SET_USER_VERIFIEDrq   )rt   r  r&   r&   r'   set_user_verified^  s   zWebDriver.set_user_verifiedc                 C   s&   d| j vr	td| tjd d S )z]Retrieves the downloadable files as a map of file names and their
        corresponding URLs.se:downloadsEnabledCYou must enable downloads in order to work with downloadable files.r   names)r)   r   r   r   GET_DOWNLOADABLE_FILESry   r&   r&   r'   get_downloadable_filesg  s   
z WebDriver.get_downloadable_files	file_nametarget_directoryc                 C   s   d| j vr	tdtj|st| | tjd|id d }tj	||}t
|d}|t| W d   n1 s@w   Y  t|d}|| W d   dS 1 s\w   Y  dS )	zDownloads a file with the specified file name to the target
        directory.

        file_name: The name of the file to download.
        target_directory: The path to the directory to save the downloaded file.
        r  r  r   r   contentsr#  Nr)r)   r   ospathexistsmakedirsr   r   DOWNLOAD_FILEr  r*  r+  base64r   zipfileZipFile
extractall)rt   r  r  r  target_filefilezip_refr&   r&   r'   download_fileo  s   

"zWebDriver.download_filec                 C   s"   d| j vr	td| tj dS )zDeletes all downloadable files.r  r  N)r)   r   r   r   DELETE_DOWNLOADABLE_FILESry   r&   r&   r'   delete_downloadable_files  s   
z#WebDriver.delete_downloadable_files)rd   TNNr{   )rL   N)r6  )NNNN)rr^   r_   r`   ra   r$   r   r"   r   r   r   r	   ru   rz   r|   typingr
   TypeBaseExceptiontypesTracebackTyper   r   r   propertyr   r   rh   r   rr   r   r   rs   r   r   r   r   r:   r   r!   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r#   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r  setterr   r  r  r  r)   boolr0  r1  ri   r)  r3  r>  rG  rK  rN  r<  rE  r=  r   rp   rT  r[  r^  r   rl  r_  r   r  r  r   r  r   r  r  r  r  r  r  r  r  r  r&   r&   r&   r'   rc      s    
.























"




 	
rc   )F)Fra   r  r   r,   r  r  r  r  r&  r  abcr   r   r   r   r   	importlibr   r   r	   r
   r   selenium.common.exceptionsr   r   r   r   r   selenium.webdriver.common.byr   !selenium.webdriver.common.optionsr   ,selenium.webdriver.common.print_page_optionsr   "selenium.webdriver.common.timeoutsr   /selenium.webdriver.common.virtual_authenticatorr   r   r   +selenium.webdriver.support.relative_locatorr   rl  r   r   r   errorhandlerr   rp   r   r   r   r   remote_connectionr    r   r!   
shadowrootr"   r   r#   
webelementr$   r%   r(   r3   rJ   r\   r]   rc   r&   r&   r&   r'   <module>   sf   
"