U
    bC                     @  s   d dl mZ d dlZd dlmZmZ d dlm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mZ d dlmZ d d	lmZ d
dlmZ d
dlmZ dadadd ZG dd dedZG dd deZdS )    )annotationsN)	b64decodeencodebytes)md5)ABCMeta)BytesIO)WebDriverExceptionJavascriptException)By)keys_to_typing   )Command)
ShadowRootc                  C  s@   d tdd d } t| ddat| ddad S )N.zgetAttribute.jsutf8zisDisplayed.js)join__name__splitpkgutilget_datadecodegetAttribute_jsisDisplayed_js)Z_pkg r   H/tmp/pip-unpacked-wheel-3sqd7awy/selenium/webdriver/remote/webelement.py_load_js(   s    r   c                   @  s   e Zd ZdZdS )BaseWebElementz
    Abstract Base Class for WebElement.
    ABC's will allow custom types to be registered as a WebElement to pass type checks.
    N)r   
__module____qualname____doc__r   r   r   r   r   0   s   r   )	metaclassc                   @  s  e Zd ZdZdd Zdd Zedddd	Zeddd
dZddddZ	dd Z
ddddZddddZddddZddddZddddZddddZdddd Zed!dd"d#Zddd$d%Zed&dd'd(Zed&dd)d*Zddd+d,Zed&dd-d.Zed&dd/d0Zeddd1d2Zeddd3d4Zeddd5d6Zed7dd8d9Zddd:d;Zed<d= Zeddd>d?Zd@dA Z dBdC Z!dPdEdFZ"e#j$dDfd ddGdHZ%e#j$dDfdIddJdKZ&dLdM Z'dNdO Z(dDS )Q
WebElementa  Represents a DOM element.

    Generally, all interesting operations that interact with a document will be
    performed through this interface.

    All method calls will do a freshness check to ensure that the element
    reference is still valid.  This essentially determines whether or not the
    element is still attached to the DOM.  If this test fails, then an
    ``StaleElementReferenceException`` is thrown, and all future calls to this
    instance will fail.c                 C  s   || _ || _d S N)_parent_id)selfparentZid_r   r   r   __init__D   s    zWebElement.__init__c                 C  s   d t| | jj| jS )Nz<<{0.__module__}.{0.__name__} (session="{1}", element="{2}")>)formattyper$   Z
session_idr%   r&   r   r   r   __repr__H   s
      zWebElement.__repr__str)returnc                 C  s   |  tjd S )z$This element's ``tagName`` property.value)_executer   ZGET_ELEMENT_TAG_NAMEr+   r   r   r   tag_nameL   s    zWebElement.tag_namec                 C  s   |  tjd S )zThe text of the element.r/   )r0   r   ZGET_ELEMENT_TEXTr+   r   r   r   textQ   s    zWebElement.textNonec                 C  s   |  tj dS )zClicks the element.N)r0   r   ZCLICK_ELEMENTr+   r   r   r   clickV   s    zWebElement.clickc                 C  s8   d}z| j ||  W n tk
r2   tdY nX dS )zSubmits a form.a  var form = arguments[0];
while (form.nodeName != "FORM" && form.parentNode) {
  form = form.parentNode;
}
if (!form) { throw Error('Unable to find containing form element'); }
if (!form.ownerDocument) { throw Error('Unable to find owning document'); }
var e = form.ownerDocument.createEvent('Event');
e.initEvent('submit', true, true);
if (form.dispatchEvent(e)) { HTMLFormElement.prototype.submit.call(form) }
z=To submit an element, it must be nested inside a form elementN)r$   execute_scriptr	   r   )r&   scriptr   r   r   submitZ   s
    
zWebElement.submitc                 C  s   |  tj dS )z-Clears the text if it's a text entry element.N)r0   r   ZCLEAR_ELEMENTr+   r   r   r   cleark   s    zWebElement.clearzstr | bool | WebElement | dictc                 C  sB   z|  tjd|id W S  tk
r<   | jd| | Y S X dS )z
        Gets the given property of the element.

        :Args:
            - name - Name of the property to retrieve.

        :Usage:
            ::

                text_length = target_element.get_property("text_length")
        namer/   z!return arguments[0][arguments[1]]N)r0   r   ZGET_ELEMENT_PROPERTYr   r'   r5   r&   r9   r   r   r   get_propertyo   s    zWebElement.get_propertyc                 C  s   |  tjd|id S )a  
        Gets the given attribute of the element. Unlike :func:`~selenium.webdriver.remote.BaseWebElement.get_attribute`,
        this method only returns attributes declared in the element's HTML markup.

        :Args:
            - name - Name of the attribute to retrieve.

        :Usage:
            ::

                text_length = target_element.get_dom_attribute("class")
        r9   r/   )r0   r   ZGET_ELEMENT_ATTRIBUTEr:   r   r   r   get_dom_attribute   s    zWebElement.get_dom_attributec                 C  s&   t dkrt  | jdt  | |}|S )a>  Gets the given attribute or property of the element.

        This method will first try to return the value of a property with the
        given name. If a property with that name doesn't exist, it returns the
        value of the attribute with the same name. If there's no attribute with
        that name, ``None`` is returned.

        Values which are considered truthy, that is equals "true" or "false",
        are returned as booleans.  All other non-``None`` values are returned
        as strings.  For attributes or properties which do not exist, ``None``
        is returned.

        To obtain the exact value of the attribute or property,
        use :func:`~selenium.webdriver.remote.BaseWebElement.get_dom_attribute` or
        :func:`~selenium.webdriver.remote.BaseWebElement.get_property` methods respectively.

        :Args:
            - name - Name of the attribute/property to retrieve.

        Example::

            # Check if the "active" CSS class is applied to an element.
            is_active = "active" in target_element.get_attribute("class")

        N#return (%s).apply(null, arguments);)r   r   r'   r5   )r&   r9   Zattribute_valuer   r   r   get_attribute   s     zWebElement.get_attributeboolc                 C  s   |  tjd S )zzReturns whether the element is selected.

        Can be used to check if a checkbox or radio button is selected.
        r/   )r0   r   ZIS_ELEMENT_SELECTEDr+   r   r   r   is_selected   s    zWebElement.is_selectedc                 C  s   |  tjd S )z'Returns whether the element is enabled.r/   )r0   r   ZIS_ELEMENT_ENABLEDr+   r   r   r   
is_enabled   s    zWebElement.is_enabledc                   s    j jr`tt fdddtt|d}d|kr`g }|D ]}| | q@d|} 	t
jdt|t|d dS )a3  Simulates typing into the element.

        :Args:
            - value - A string for typing, or setting form fields.  For setting
              file inputs, this could be a local file path.

        Use this to send simple key events or to fill out form fields::

            form_textfield = driver.find_element(By.NAME, 'username')
            form_textfield.send_keys("admin")

        This can also be used to set file inputs.

        ::

            file_input = driver.find_element(By.NAME, 'profilePic')
            file_input.send_keys("path/to/profilepic.gif")
            # Generally it's better to wrap the file path in one of the methods
            # in os.path to return the actual path to support cross OS testing.
            # file_input.send_keys(os.path.abspath("path/to/profilepic.gif"))

        c                   s    j jt| S r#   )r'   Zfile_detectorZis_local_filer-   )Zkeys_to_sendr+   r   r   <lambda>   s    z&WebElement.send_keys.<locals>.<lambda> 
N)r2   r/   )r'   Z
_is_remotelistmapr   r-   r   append_uploadr0   r   ZSEND_KEYS_TO_ELEMENTr   )r&   r/   Zlocal_filesZremote_filesfiler   r+   r   	send_keys   s    
zWebElement.send_keysr   c                 C  sd   t | jjd dd }| jjd  dks6td|dkrTtd| jjd  | tjd	 S )
am  
            Returns a shadow root of the element if there is one or an error. Only works from
            Chromium 96 onwards. Previous versions of Chromium based browsers will throw an
            assertion exception.

            :Returns:
              - ShadowRoot object or
              - NoSuchShadowRoot - if no shadow root was attached to element
        ZbrowserVersionr   r   ZbrowserName)ZfirefoxZsafariz4This only currently works in Chromium based browsers_   zJPlease use Chromium based browsers with version 96 or later. Version used r/   )	intr$   Zcapsr   lowerAssertionErrorr0   r   ZGET_SHADOW_ROOT)r&   Zbrowser_main_versionr   r   r   shadow_root   s    zWebElement.shadow_rootc                 C  s    t dkrt  | jdt  | S )z)Whether the element is visible to a user.Nr=   )r   r   r'   r5   r+   r   r   r   is_displayed   s    zWebElement.is_displayeddictc                 C  s4   |  tjd| gdd }t|d t|d dS )aF  THIS PROPERTY MAY CHANGE WITHOUT WARNING. Use this to discover
        where on the screen an element is so that we can click it. This method
        should cause the element to be scrolled into view.

        Returns the top lefthand corner location on the screen, or ``None`` if
        the element is not visible.

        zNarguments[0].scrollIntoView(true); return arguments[0].getBoundingClientRect())r6   argsr/   xyrS   rT   )r0   r   ZW3C_EXECUTE_SCRIPTround)r&   old_locr   r   r    location_once_scrolled_into_view   s    


z+WebElement.location_once_scrolled_into_viewc                 C  s&   |  tjd }|d |d d}|S )zThe size of the element.r/   heightwidth)rY   rZ   r0   r   GET_ELEMENT_RECT)r&   sizeZnew_sizer   r   r   r]     s
    zWebElement.sizec                 C  s   |  tjd|id S )zThe value of a CSS property.ZpropertyNamer/   )r0   r   Z!GET_ELEMENT_VALUE_OF_CSS_PROPERTY)r&   Zproperty_namer   r   r   value_of_css_property  s     z WebElement.value_of_css_propertyc                 C  s.   |  tjd }t|d t|d d}|S )z5The location of the element in the renderable canvas.r/   rS   rT   rU   )r0   r   r\   rV   )r&   rW   Znew_locr   r   r   location  s
    

zWebElement.locationc                 C  s   |  tjd S )z7A dictionary with the size and location of the element.r/   r[   r+   r   r   r   rect#  s    zWebElement.rectc                 C  s   |  tjd S )z1 Returns the ARIA role of the current web elementr/   )r0   r   ZGET_ELEMENT_ARIA_ROLEr+   r   r   r   	aria_role(  s    zWebElement.aria_rolec                 C  s   |  tjd S )z0Returns the ARIA Level of the current webelementr/   )r0   r   ZGET_ELEMENT_ARIA_LABELr+   r   r   r   accessible_name-  s    zWebElement.accessible_namec                 C  s   |  tjd S )z
        Gets the screenshot of the current element as a base64 encoded string.

        :Usage:
            ::

                img_b64 = element.screenshot_as_base64
        r/   )r0   r   ZELEMENT_SCREENSHOTr+   r   r   r   screenshot_as_base642  s    
zWebElement.screenshot_as_base64bytesc                 C  s   t | jdS )z
        Gets the screenshot of the current element as a binary data.

        :Usage:
            ::

                element_png = element.screenshot_as_png
        ascii)r   rc   encoder+   r   r   r   screenshot_as_png>  s    
zWebElement.screenshot_as_pngc              	   C  sn   |  dstdt | j}zDz$t|d}|| W 5 Q R X W n tk
r`   Y W 
dS X W 5 ~X dS )a  
        Saves a screenshot of the current element 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:
            ::

                element.screenshot('/Screenshots/foo.png')
        z.pngz^name used for saved screenshot does not match file type. It should end with a `.png` extensionwbFT)	rM   endswithwarningswarnUserWarningrg   openwriteOSError)r&   filenameZpngfr   r   r   
screenshotJ  s    zWebElement.screenshotc                 C  s   | j S )zIInternal reference to the WebDriver instance this element was found from.)r$   r+   r   r   r   r'   f  s    zWebElement.parentc                 C  s   | j S )a  Internal ID used by selenium.

        This is mainly for internal use. Simple use cases such as checking if 2
        webelements refer to the same element, can be done using ``==``::

            if element1 == element2:
                print("These 2 are equal")

        )r%   r+   r   r   r   idk  s    zWebElement.idc                 C  s   t |do| j|jkS )Nrs   )hasattrr%   rs   r&   elementr   r   r   __eq__x  s    zWebElement.__eq__c                 C  s   |  | S r#   )rw   ru   r   r   r   __ne__{  s    zWebElement.__ne__Nc                 C  s    |si }| j |d< | j||S )a9  Executes a command against the underlying HTML element.

        Args:
          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.
        rs   )r%   r$   execute)r&   commandparamsr   r   r   r0     s    

zWebElement._executec                 C  sd   |t jkrt j}d| }n2|t jkr4t j}d| }n|t jkrLt j}d| }| tj||dd S )z
        Find an element given a By strategy and locator.

        :Usage:
            ::

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

        :rtype: WebElement
        	[id="%s"].%s[name="%s"]Zusingr/   r/   )r
   IDCSS_SELECTOR
CLASS_NAMENAMEr0   r   ZFIND_CHILD_ELEMENTr&   Zbyr/   r   r   r   find_element  s    




zWebElement.find_elementzlist[WebElement]c                 C  sd   |t jkrt j}d| }n2|t jkr4t j}d| }n|t jkrLt j}d| }| tj||dd S )z
        Find elements given a By strategy and locator.

        :Usage:
            ::

                element = element.find_elements(By.CLASS_NAME, 'foo')

        :rtype: list of WebElement
        r|   r}   r~   r   r/   )r
   r   r   r   r   r0   r   ZFIND_CHILD_ELEMENTSr   r   r   r   find_elements  s    




zWebElement.find_elementsc                 C  s   t t| jd dS )Nutf-8   )rL   md5_hashr%   rf   	hexdigestr+   r   r   r   __hash__  s    zWebElement.__hash__c              
   C  s   t  }t|dtj}||tj|d  |  t	|
 }t|tsV|d}z| tjd|id W S  tk
r } zNd| kr| W Y 8S d| kr| W Y  S d| kr| W Y S  W 5 d }~X Y nX d S )	Nwr   r   rI   r/   zUnrecognized command: POSTzCommand not found: POST z.{"status":405,"value":["GET","HEAD","DELETE"]})r   zipfileZipFileZIP_DEFLATEDrn   ospathr   closer   getvalue
isinstancer-   r   r0   r   ZUPLOAD_FILEr   __str__)r&   rp   fpZzippedcontenter   r   r   rH     s"    

zWebElement._upload)N))r   r   r   r    r(   r,   propertyr1   r2   r4   r7   r8   r;   r<   r>   r@   rA   rJ   rO   rP   rX   r]   r^   r_   r`   ra   rb   rc   rg   rr   r'   rs   rw   rx   r0   r
   r   r   r   r   rH   r   r   r   r   r"   8   s`   !'	

r"   ) 
__future__r   r   base64r   r   hashlibr   r   r   rj   r   abcr   ior   Zselenium.common.exceptionsr   r	   Zselenium.webdriver.common.byr
   Zselenium.webdriver.common.utilsr   rz   r   Z
shadowrootr   r   r   r   r   r"   r   r   r   r   <module>   s$   