o
    _c                    @   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mZ ddl	m
Z
mZmZmZmZmZ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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*m+Z+m,Z, ddl-m.Z. ddl/m0Z0m1Z1m2Z2 ddl3m4Z4 ddl5m6Z6 ddl7m8Z8 e
rddl9m:Z:m;Z; e<e=Z>G dd deZ?dZ@dddddZAd edeBeCeDf d!eeC fd"d#ZEG d$d% d%eFZGdS )&zPage module.    N)SimpleNamespace)TYPE_CHECKINGAny	AwaitableCallableDictListOptionalUnion)EventEmitter)helper)
CDPSession)Coverage)Dialog)ElementHandle)EmulationManager)	PageError)JSHandle)Frame)FrameManager)
debugError)KeyboardMouseTouchscreen)NavigatorWatcher)NetworkManagerRequestResponse)Tracing)
merge_dict)Worker)BrowserTargetc                       s  e Zd ZU dZedi dddddddd	d
dddddddddddddddddddddd d!d"d#Zed$d%d&d$d'd&d%d(d&d(d%d&d)d*d&d+d)d&d,d+d&d-d,d&d.d-d&d/d.d&d0
Zee	ee	e
f f ed1< e	2dd3ed4d5d6ed7ee d8ed9d fd:d;Z	2dd3ed4d5d<ed6ed8ed9d2f fd=d>Zedd?d@ZeddBdCZdDedEed9d2fdFdGZdHed9d2fdIdJZed9edK fdLdMZed9efdNdOZed9efdPdQZed9efdRdSZdTe	d9d2fdUdVZ eddXdYZ!ed9e"dK fdZd[Z#ed9e"e$ fd\d]Z%d^ed9d2fd_d`Z&daed9d2fdbdcZ'dde(d9d2fdedfZ)dge	dhed9d2fdidjZ*dHed9d2fdkdlZ+dTe	d9ee, fdmdnZ-doe	dDed9e.fdpdqZ/dre.d9e.fdsdtZ0dTe	doe	dDed9efdudvZ1dTe	doe	dDed9efdwdxZ2dTe	d9e"e, fdydzZ3d{e	d9e"e, fd|d}Z4e-Z5e1Z6e3Z7e2Z8e4Z9d~e	d9e"ee	e:e	e(ef f  fddZ;ded9d2fddZ<ded9d2fddZ=ddedEe	d9e,fddZ>ddedEe	d9e,fddZ?de	d9e	fddZ@de	deAdef d9d2fddZBdee	e	f d9efddZCdee	e	f d9d2fddZDde	d9d2fddZEd9ee	ef fddZFdHed9d2fddZGde"d9ee	ef fddZHded9d2fddZIdHed9d2fddZJdHed9d2fddZKde	dDe"e. d9d2fddZLdHed9d2fddZMed9e	fddZNd9e	fddZOde	d9d2fddZPdde	dedEed9eeQ fddZRde	de	d9ee	 fddZSddedEed9eeQ fddZTddedEed9eeQ fddZU	2dde:e	eAeVgef f dedEed9eVfddZW	2dde:e	eAeQgef f dedEed9eQfddÄZXddedEed9eeQ fddńZYddedEed9eeQ fddǄZZde(ded9eeQ fddʄZ[ddd̄Z\ddedEed9d2fdd΄Z]daed9d2fddЄZ^daed9d2fdd҄Z_dde	d9d2fddՄZ`ded9d2fdd؄Zaed9ee fddڄZbddܜdoe	dDeded9efdd߄Zcdoe	dDe	d9d2fddZdddaed9d2fddZeddedEed9e:efe	f fddZgde	ded9e:efe	f fddZhddedEed9effddZid9e	fddZjd9e	fddZkddedEed9d2fddZld9efddZmed9enfddZoddTe	dedEed9d2fddZpdTe	d9d2fddZqdTe	d9d2fddZrdTe	de	d9e"e	 fddZsddTe	de	dedEed9d2f
d dZt	2dde:e	e(e
f dedDedEed9euf
ddZvddTe	dedEed9eufddZwdde	dedEed9eufdd	Zxddoe	dedDe	dEed9euf
d
dZy  ZzS (  Pagea  Page class.

    This class provides methods to interact with a single tab of chrome. One
    :class:`~pyppeteer.browser.Browser` object might have multiple Page object.

    The :class:`Page` class emits various :attr:`~Page.Events` which can be
    handled by using ``on`` or ``once`` method, which is inherited from
    `pyee <https://pyee.readthedocs.io/en/latest/>`_'s ``EventEmitter`` class.
    ClosecloseConsoleconsoler   dialogDOMContentLoadedZdomcontentloadedErrorerrorr   Z	pageerrorr   requestr   responseRequestFailedZrequestfailedRequestFinishedZrequestfinishedFrameAttachedZframeattachedFrameDetachedZframedetachedFrameNavigatedZframenavigatedLoadloadMetricsmetricsWorkerCreatedZworkercreatedWorkerDestroyedZworkerdestroyed      !@   )widthheight      ǧ@@gffffffG@gffffff7@g     0@gffffff'@g
ףp= @gRQ@)
letterZlegalZtabloidledgerZa0Za1Za2a3Za4Za5PaperFormatsNclienttargetr"   ignoreHTTPSErrorsdefaultViewportscreenshotTaskQueuereturnc                    s   |  dI dH f |  dI dH d }t| ||||}t|  dddd|  d	d
di|  di |  di |  di |  di |  di I dH  |rX|  dddiI dH  |rb||I dH  |S )z+Async function which makes new page object.zPage.enableNzPage.getFrameTree	frameTreezTarget.setAutoAttachTF)Z
autoAttachZwaitForDebuggerOnStartzPage.setLifecycleEventsEnabledenabledzNetwork.enablezRuntime.enablezSecurity.enablezPerformance.enablez
Log.enablez#Security.setIgnoreCertificateErrorsignore)sendr#   asynciogathersetViewport)rC   rD   rE   rF   rG   rI   page rQ   9/usr/local/lib/python3.10/dist-packages/pyppeteer/page.pycreateU   s$   	





	zPage.createrI   c                    s  t    d_ _|_t _t j_t	 j_
t |_t j_t _t _i _|_d_d_t _d _|d u rSg }|_i _dtdd f fdd}dtdd ffdd	} d
|  d| j}|tjjfdd |tjj fdd |tjj!fdd j}	|	tjj"fdd |	tjj#fdd |	tjj$fdd |	tjj%fdd  dfdd  dfdd  dfdd  dfdd  dfdd  dfdd  d fd!d  d"fd#d  d$fd%d d&t&j'j(dd ffd'd(}
jj)*|
 d S ))NF0u  TeventrH   c              
      s   | d }|d dkr0z  dd| d i W d S  ty/ } ztt| W Y d }~d S d }~ww | d } |d |}t||d jj}|j|< 	t
jj| d S )N
targetInfotypeworkerzTarget.detachFromTarget	sessionIdurl)rL   	Exceptionr   loggerZ_createSessionr    _addConsoleMessage_handleException_workersemitr#   Eventsr7   )rU   rV   erY   sessionrX   rC   selfrQ   rR   _onTargetAttached   s   
z(Page.__init__.<locals>._onTargetAttachedc                    s<   | d } j |}|d u rd S  tjj|  j |= d S )NrY   )r_   getr`   r#   ra   r8   )rU   rY   rX   re   rQ   rR   _onTargetDetached   s   z(Page.__init__.<locals>._onTargetDetachedzTarget.attachedToTargetzTarget.detachedFromTargetc                         tjj| S N)r`   r#   ra   r0   rU   rh   rQ   rR   <lambda>       zPage.__init__.<locals>.<lambda>c                    rj   rk   )r`   r#   ra   r1   rl   rh   rQ   rR   rm      rn   c                    rj   rk   )r`   r#   ra   r2   rl   rh   rQ   rR   rm      rn   c                    rj   rk   )r`   r#   ra   r   rl   rh   rQ   rR   rm      rn   c                    rj   rk   )r`   r#   ra   r   rl   rh   rQ   rR   rm      rn   c                    rj   rk   )r`   r#   ra   r.   rl   rh   rQ   rR   rm      rn   c                    rj   rk   )r`   r#   ra   r/   rl   rh   rQ   rR   rm      rn   zPage.domContentEventFiredc                         tjjS rk   )r`   r#   ra   r)   rl   rh   rQ   rR   rm          zPage.loadEventFiredc                    ro   rk   )r`   r#   ra   r3   rl   rh   rQ   rR   rm      rp   zRuntime.consoleAPICalledc                    
     | S rk   )_onConsoleAPIrl   rh   rQ   rR   rm         
 zRuntime.bindingCalledc                    rq   rk   )_onBindingCalledrl   rh   rQ   rR   rm      rs   zPage.javascriptDialogOpeningc                    rq   rk   )	_onDialogrl   rh   rQ   rR   rm      rs   zRuntime.exceptionThrownc                    s     | dS )NexceptionDetails)r^   rg   )	exceptionrh   rQ   rR   rm      rn   zInspector.targetCrashedc                    s      S rk   )_onTargetCrashedrl   rh   rQ   rR   rm      s    zPerformance.metricsc                    rq   rk   )_emitMetricsrl   rh   rQ   rR   rm      rs   zLog.entryAddedc                    rq   rk   )_onLogEntryAddedrl   rh   rQ   rR   rm      rs   futc                    s     tjj d _d S )NT)r`   r#   ra   r$   _closed)r{   rh   rQ   rR   closed   s   
zPage.__init__.<locals>.closed)+super__init__r|   _client_targetr   	_keyboardr   _mouser   _touchscreenr   _frameManagerr   _networkManagerr   _emulationManagerr   _tracing_pageBindings_ignoreHTTPSErrors_defaultNavigationTimeout_javascriptEnabledr   	_coverage	_viewportZ_screenshotTaskQueuer_   r   onra   r0   r1   r2   r   r   r.   r/   rM   futuresFuture_isClosedPromiseadd_done_callback)re   rC   rD   rI   rE   rG   rf   ri   Z_fmZ_nmr}   	__class__rd   rR   r   q   sZ   




zPage.__init__c                 C      | j S )z'Return a target this page created from.)r   rh   rQ   rQ   rR   rD         zPage.targetr!   c                 C      | j jS )z$Get the browser the page belongs to.)r   browserrh   rQ   rQ   rR   r         zPage.browserargskwargsc                 O   s   |  dtd d S )Nr+   zPage crashed!)r`   r   )re   r   r   rQ   rQ   rR   rx      s   zPage._onTargetCrashedrU   c                 C   sz   | di }| dd}| dd}| dg }| dd}|D ]	}t| j| q |dkr;| tjjt|| d S d S )Nentrylevel textr   sourcerX   )	rg   r   ZreleaseObjectr   r`   r#   ra   r&   ConsoleMessage)re   rU   r   r   r   r   r   argrQ   rQ   rR   rz      s   zPage._onLogEntryAddedr   c                 C   r   )z>Get main :class:`~pyppeteer.frame_manager.Frame` of this page.)r   Z
_mainFramerh   rQ   rQ   rR   	mainFrame   r   zPage.mainFramec                 C   r   )z.Get :class:`~pyppeteer.input.Keyboard` object.)r   rh   rQ   rQ   rR   keyboard   r   zPage.keyboardc                 C   r   )z1Get :class:`~pyppeteer.input.Touchscreen` object.)r   rh   rQ   rQ   rR   touchscreen   r   zPage.touchscreenc                 C   r   )z-Return :class:`~pyppeteer.coverage.Coverage`.)r   rh   rQ   rQ   rR   coverage   r   zPage.coverageselectorc                    ,   | j }|du rtd||I dH  dS )z{Tap the element which matches the ``selector``.

        :arg str selector: A selector to search element to touch.
        Nzno main frame)r   r   tapre   r   framerQ   rQ   rR   r      
   zPage.tapr   c                 C   r   )zGet tracing object.)r   rh   rQ   rQ   rR   tracing   r   zPage.tracingc                 C      t | j S )zGet all frames of this page.)listr   framesrh   rQ   rQ   rR   r        zPage.framesc                 C   r   )zGet all workers of this page.)r   r_   valuesrh   rQ   rQ   rR   workers  r   zPage.workersvaluec                       | j |I dH S )a  Enable/disable request interception.

        Activating request interception enables
        :class:`~pyppeteer.network_manager.Request` class's
        :meth:`~pyppeteer.network_manager.Request.abort`,
        :meth:`~pyppeteer.network_manager.Request.continue_`, and
        :meth:`~pyppeteer.network_manager.Request.response` methods.
        This provides the capability to modify network requests that are made
        by a page.

        Once request interception is enabled, every request will stall unless
        it's continued, responded or aborted.

        An example of a native request interceptor that aborts all image
        requests:

        .. code:: python

            browser = await launch()
            page = await browser.newPage()
            await page.setRequestInterception(True)

            async def intercept(request):
                if request.url.endswith('.png') or request.url.endswith('.jpg'):
                    await request.abort()
                else:
                    await request.continue_()

            page.on('request', lambda req: asyncio.ensure_future(intercept(req)))
            await page.goto('https://example.com')
            await browser.close()
        N)r   setRequestInterception)re   r   rQ   rQ   rR   r     s   !zPage.setRequestInterceptionrJ   c                    s   | j |I dH  dS )z Set offline mode enable/disable.N)r   setOfflineModere   rJ   rQ   rQ   rR   r   /     zPage.setOfflineModetimeoutc                 C   s
   || _ dS )a  Change the default maximum navigation timeout.

        This method changes the default timeout of 30 seconds for the following
        methods:

        * :meth:`goto`
        * :meth:`goBack`
        * :meth:`goForward`
        * :meth:`reload`
        * :meth:`waitForNavigation`

        :arg int timeout: Maximum navigation time in milliseconds. Pass ``0``
                          to disable timeout.
        N)r   )re   r   rQ   rQ   rR   setDefaultNavigationTimeout3  s   
z Page.setDefaultNavigationTimeoutmethodmsgc              
      sN   z| j ||I d H  W d S  ty& } ztt| W Y d }~d S d }~ww rk   )r   rL   r[   r   r\   )re   r   r   rb   rQ   rQ   rR   _sendD     z
Page._sendc                 C   s0   | j sd S | jj| d|ddd d S )NzSecurity.handleCertificateErroreventIdcontinue)r   action)r   r   _loopcreate_taskr   rg   re   rU   rQ   rQ   rR   _onCertificateErrorJ  s
   zPage._onCertificateErrorc                    $   | j }|s
td||I dH S )aK  Get an Element which matches ``selector``.

        :arg str selector: A selector to search element.
        :return Optional[ElementHandle]: If element which matches the
            ``selector`` is found, return its
            :class:`~pyppeteer.element_handle.ElementHandle`. If not found,
            returns ``None``.
        no main frame.N)r   r   querySelectorr   rQ   rQ   rR   r   Q  
   	zPage.querySelectorpageFunctionc                    sD   | j std| j  I dH }|std|j|g|R  I dH S )a-  Execute function on this page.

        Difference between :meth:`~pyppeteer.page.Page.evaluate` and
        :meth:`~pyppeteer.page.Page.evaluateHandle` is that
        ``evaluateHandle`` returns JSHandle object (not value).

        :arg str pageFunction: JavaScript function to be executed.
        r   NNo context.)r   r   executionContextevaluateHandle)re   r   r   contextrQ   rQ   rR   r   _  s   	zPage.evaluateHandleprototypeHandlec                    s<   | j std| j  I dH }|std||I dH S )zIterate js heap and finds all the objects with the handle.

        :arg JSHandle prototypeHandle: JSHandle of prototype object.
        r   Nr   )r   r   r   queryObjects)re   r   r   rQ   rQ   rR   r   o  s   zPage.queryObjectsc                    .   | j }|s
td|j||g|R  I dH S )a  Execute function with an element which matches ``selector``.

        :arg str selector: A selector to query page for.
        :arg str pageFunction: String of JavaScript function to be evaluated on
                               browser. This function takes an element which
                               matches the selector as a first argument.
        :arg Any args: Arguments to pass to ``pageFunction``.

        This method raises error if no element matched the ``selector``.
        r   N)r   r   querySelectorEvalre   r   r   r   r   rQ   rQ   rR   r   {  s
   zPage.querySelectorEvalc                    r   )a  Execute function with all elements which matches ``selector``.

        :arg str selector: A selector to query page for.
        :arg str pageFunction: String of JavaScript function to be evaluated on
                               browser. This function takes Array of the
                               matched elements as the first argument.
        :arg Any args: Arguments to pass to ``pageFunction``.
        r   N)r   r   querySelectorAllEvalr   rQ   rQ   rR   r     s
   	zPage.querySelectorAllEvalc                    r   )a[  Get all element which matches ``selector`` as a list.

        :arg str selector: A selector to search element.
        :return List[ElementHandle]: List of
            :class:`~pyppeteer.element_handle.ElementHandle` which matches the
            ``selector``. If no element is matched to the ``selector``, return
            empty list.
        r   N)r   r   querySelectorAllr   rQ   rQ   rR   r     r   zPage.querySelectorAll
expressionc                    r   )zEvaluate the XPath expression.

        If there are no such elements in this page, return an empty list.

        :arg str expression: XPath string to be evaluated.
        r   N)r   r   xpath)re   r   r   rQ   rQ   rR   r     s
   z
Page.xpathurlsc                    s2   |s| j f}| jdd|iI dH }|di S )aR  Get cookies.

        If no URLs are specified, this method returns cookies for the current
        page URL. If URLs are specified, only cookies for those URLs are
        returned.

        Returned cookies are list of dictionaries which contain these fields:

        * ``name`` (str)
        * ``value`` (str)
        * ``url`` (str)
        * ``domain`` (str)
        * ``path`` (str)
        * ``expires`` (number): Unix time in seconds
        * ``httpOnly`` (bool)
        * ``secure`` (bool)
        * ``session`` (bool)
        * ``sameSite`` (str): ``'Strict'`` or ``'Lax'``
        zNetwork.getCookiesr   Ncookies)rZ   r   rL   rg   )re   r   resprQ   rQ   rR   r     s
   zPage.cookiesr   c                    sT   | j }|D ]!}tdi |}|ds|dr||d< | jd|I dH  qdS )zDelete cookie.

        ``cookies`` should be dictionaries which contain these fields:

        * ``name`` (str): **required**
        * ``url`` (str)
        * ``domain`` (str)
        * ``path`` (str)
        * ``secure`` (bool)
        rZ   httpzNetwork.deleteCookiesNrQ   )rZ   dictrg   
startswithr   rL   )re   r   pageURLcookieitemrQ   rQ   rR   deleteCookie  s   zPage.deleteCookiec                    s   | j }|d}g }|D ]D}tdi |}d|vr |r ||d< |ddkr5|dd}td| d|dddrL|dd}td	| d|| q| j| I d
H  |rj| jdd|iI d
H  d
S d
S )a  Set cookies.

        ``cookies`` should be dictionaries which contain these fields:

        * ``name`` (str): **required**
        * ``value`` (str): **required**
        * ``url`` (str)
        * ``domain`` (str)
        * ``path`` (str)
        * ``expires`` (number): Unix time in seconds
        * ``httpOnly`` (bool)
        * ``secure`` (bool)
        * ``sameSite`` (str): ``'Strict'`` or ``'Lax'``
        r   rZ   zabout:blanknamer   z Blank page can not have cookie ""zdata:z#Data URL page can not have cookie "NzNetwork.setCookiesr   rQ   )	rZ   r   r   rg   r   appendr   r   rL   )re   r   r   ZstartsWithHTTPitemsr   r   r   rQ   rQ   rR   	setCookie  s&   
zPage.setCookieoptionsc                    .   | j }|s
tdt||}||I dH S )a  Add script tag to this page.

        One of ``url``, ``path`` or ``content`` option is necessary.
            * ``url`` (string): URL of a script to add.
            * ``path`` (string): Path to the local JavaScript file to add.
            * ``content`` (string): JavaScript string to add.
            * ``type`` (string): Script type. Use ``module`` in order to load a
              JavaScript ES6 module.

        :return ElementHandle: :class:`~pyppeteer.element_handle.ElementHandle`
                               of added tag.
        r   N)r   r   r   addScriptTagre   r   r   r   rQ   rQ   rR   r   
  s   
zPage.addScriptTagc                    r   )a  Add style or link tag to this page.

        One of ``url``, ``path`` or ``content`` option is necessary.
            * ``url`` (string): URL of the link tag to add.
            * ``path`` (string): Path to the local CSS file to add.
            * ``content`` (string): CSS string to add.

        :return ElementHandle: :class:`~pyppeteer.element_handle.ElementHandle`
                               of added tag.
        r   N)r   r   r   addStyleTagr   rQ   rQ   rR   r     s   
zPage.addStyleTagfilePathc                    r   )zu[Deprecated] Inject file to this page.

        This method is deprecated. Use :meth:`addScriptTag` instead.
        r   N)r   r   
injectFile)re   r   r   rQ   rQ   rR   r   .  s
   zPage.injectFiler   pyppeteerFunction.c                    s   | j |rtd| d| d|| j |< d}t||| jdd|iI dH  | jdd	iI dH  d
tdtddfdd t	
 fdd| jD I dH  dS )a  Add python function to the browser's ``window`` object as ``name``.

        Registered function can be called from chrome process.

        :arg string name: Name of the function on the window object.
        :arg Callable pyppeteerFunction: Function which will be called on
                                         python process. This function should
                                         not be asynchronous function.
        z%Failed to add page binding with name z
: window["z"] already exists!a  
function addPageBinding(bindingName) {
  const binding = window[bindingName];
  window[bindingName] = async(...args) => {
    const me = window[bindingName];
    let callbacks = me['callbacks'];
    if (!callbacks) {
      callbacks = new Map();
      me['callbacks'] = callbacks;
    }
    const seq = (me['lastSeq'] || 0) + 1;
    me['lastSeq'] = seq;
    const promise = new Promise(fulfill => callbacks.set(seq, fulfill));
    binding(JSON.stringify({name: bindingName, seq, args}));
    return promise;
  };
}
        zRuntime.addBindingr   N%Page.addScriptToEvaluateOnNewDocumentr   r   r   rH   c              
      sN   z| j |ddI d H  W d S  ty& } ztt| W Y d }~d S d }~ww )NT
force_expr)evaluater[   r   r\   )r   r   rb   rQ   rQ   rR   	_evaluate\  r   z&Page.exposeFunction.<locals>._evaluatec                    s   g | ]} |qS rQ   rQ   ).0r   r   r   rQ   rR   
<listcomp>b  s    z'Page.exposeFunction.<locals>.<listcomp>)r   rg   r   r   evaluationStringr   rL   r   strrM   waitr   )re   r   r   ZaddPageBindingrQ   r   rR   exposeFunction8  s   

&zPage.exposeFunctioncredentialsc                    r   )zProvide credentials for http authentication.

        ``credentials`` should be ``None`` or dict which has ``username`` and
        ``password`` field.
        N)r   authenticate)re   r   rQ   rQ   rR   r   d  s   zPage.authenticateheadersc                    r   )a  Set extra HTTP headers.

        The extra HTTP headers will be sent with every request the page
        initiates.

        .. note::
            ``page.setExtraHTTPHeaders`` does not guarantee the order of
            headers in the outgoing requests.

        :arg Dict headers: A dictionary containing additional http headers to
                           be sent with every requests. All header values must
                           be string.
        N)r   setExtraHTTPHeaders)re   r   rQ   rQ   rR   r   l  s   zPage.setExtraHTTPHeaders	userAgentc                    r   )zqSet user agent to use in this page.

        :arg str userAgent: Specific user agent to use in this page
        N)r   setUserAgent)re   r  rQ   rQ   rR   r  |  s   zPage.setUserAgentc                    s"   | j dI dH }| |d S )aG  Get metrics.

        Returns dictionary containing metrics as key/value pairs:

        * ``Timestamp`` (number): The timestamp when the metrics sample was
          taken.
        * ``Documents`` (int): Number of documents in the page.
        * ``Frames`` (int): Number of frames in the page.
        * ``JSEventListeners`` (int): Number of events in the page.
        * ``Nodes`` (int): Number of DOM nodes in the page.
        * ``LayoutCount`` (int): Total number of full partial page layout.
        * ``RecalcStyleCount`` (int): Total number of page style
          recalculations.
        * ``LayoutDuration`` (int): Combined duration of page duration.
        * ``RecalcStyleDuration`` (int): Combined duration of all page style
          recalculations.
        * ``ScriptDuration`` (int): Combined duration of JavaScript
          execution.
        * ``TaskDuration`` (int): Combined duration of all tasks performed by
          the browser.
        * ``JSHeapUsedSize`` (float): Used JavaScript heap size.
        * ``JSHeapTotalSize`` (float): Total JavaScript heap size.
        zPerformance.getMetricsNr6   )r   rL   _buildMetricsObject)re   r-   rQ   rQ   rR   r6     s   zPage.metricsc                 C   s(   |  tjj|d | |d d d S )Ntitler6   )r  r6   )r`   r#   ra   r5   r  r   rQ   rQ   rR   ry     s   zPage._emitMetricsc                 C   s2   i }|pg D ]}|d t v r|d ||d < q|S )Nr   r   )supportedMetrics)re   r6   resultZmetricrQ   rQ   rR   r    s   zPage._buildMetricsObjectrv   c                 C   s"   t |}| tjjt| d S rk   )r   ZgetExceptionMessager`   r#   ra   r   )re   rv   messagerQ   rQ   rR   r^     s   
zPage._handleExceptionc                 C   sR   |d }| j |}g }|dg D ]}|| j || q| |d | d S )NexecutionContextIdr   rW   )r   ZexecutionContextByIdrg   r   ZcreateJSHandler]   )re   rU   Z_idr   r   r   rQ   rQ   rR   rr     s   zPage._onConsoleAPIc           
   
   C   s   t |d }|d }|d }|d }| j| | }d}t||||}z| jd||d d W d S  tyL }	 ztt	|	 W Y d }	~	d S d }	~	ww )	Npayloadr   seqr   z
            function deliverResult(name, seq, result) {
                window[name]['callbacks'].get(seq)(result);
                window[name]['callbacks'].delete(seq);
            }
        zRuntime.evaluater  )r   Z	contextId)
jsonloadsr   r   r   r   rL   r[   r   r\   )
re   rU   objr   r
  r   r  ZdeliverResultr   rb   rQ   rQ   rR   rt     s   zPage._onBindingCalledrW   c                 C   s   |  tjjs|D ]}| jj|  q	d S g }|D ]}|j}|	dr-|
|  q|
tt| qt|d||}| tjj| d S )NZobjectId )Z	listenersr#   ra   r&   r   r   r   ZdisposeZ_remoteObjectrg   r   ZtoStringr   r   ZvalueFromRemoteObjectr   joinr`   )re   rW   r   r   Z
textTokensZremoteObjectr  rQ   rQ   rR   r]     s   
zPage._addConsoleMessagec                 C   s   d}| d}|dkrtjj}n|dkrtjj}n|dkr"tjj}n|dkr*tjj}t| j|| d| d}| t	j
j| d S )	Nr   rW   alertZconfirmpromptZbeforeunloadr  ZdefaultPrompt)rg   r   TypeZAlertZConfirmPromptZBeforeUnloadr   r`   r#   ra   )re   rU   Z
dialogType_typer(   rQ   rQ   rR   ru     s   



zPage._onDialogc                 C   s   | j }|s	td|jS )zGet URL of this page.r   )r   r   rZ   re   r   rQ   rQ   rR   rZ     s   zPage.urlc                    s&   | j }|du rtd| I dH S )z]Get the full HTML contents of the page.

        Returns HTML including the doctype.
        NNo main frame.)r   r   contentr  rQ   rQ   rR   r    s
   zPage.contenthtmlc                    r   )z]Set content to this page.

        :arg str html: HTML markup to assign to the page.
        Nr  )r   r   
setContent)re   r  r   rQ   rQ   rR   r    r   zPage.setContentrZ   c                    s   t ||}| jj}|du rtd| j dd}i  dtddf fdd}t	| jt
jj|g}|d	| j}t| j|||}	| ||I dH }
|
durSt|
|	 I dH }
|	  t| |
d
   }|ro| |j}|rz|jS dS )a  Go to the ``url``.

        :arg string url: URL to navigate page to. The url should include
                         scheme, e.g. ``https://``.

        Available options are:

        * ``timeout`` (int): Maximum navigation time in milliseconds, defaults
          to 30 seconds, pass ``0`` to disable timeout. The default value can
          be changed by using the :meth:`setDefaultNavigationTimeout` method.
        * ``waitUntil`` (str|List[str]): When to consider navigation succeeded,
          defaults to ``load``. Given a list of event strings, navigation is
          considered to be successful after all events have been fired. Events
          can be either:

          * ``load``: when ``load`` event is fired.
          * ``domcontentloaded``: when the ``DOMContentLoaded`` event is fired.
          * ``networkidle0``: when there are no more than 0 network connections
            for at least 500 ms.
          * ``networkidle2``: when there are no more than 2 network connections
            for at least 500 ms.

        The ``Page.goto`` will raise errors if:

        * there's an SSL error (e.g. in case of self-signed certificates)
        * target URL is invalid
        * the ``timeout`` is exceeded during navigation
        * then main resource failed to load

        .. note::
            :meth:`goto` either raise error or return a main resource response.
            The only exceptions are navigation to ``about:blank`` or navigation
            to the same URL with a different hash, which would succeed and
            return ``None``.

        .. note::
            Headless mode doesn't support navigation to a PDF document.
        Nr  Zrefererr   reqrH   c                    s   | j  vr|  | j < d S d S rk   )rZ   )r  requestsrQ   rR   set_request4  s   
zPage.goto.<locals>.set_requestr   r   )r   r   r   r   r   ZextraHTTPHeadersrg   r   r   addEventListenerr   ra   r   r   	_navigatenavigationPromisecancelremoveEventListenerspoprw   Z_navigationURLr-   )re   rZ   r   r   r   referrerr  ZeventListenersr   watcherr  r+   r,   rQ   r  rR   goto  s,   
'
z	Page.gotor$  c                    s<   | j d||dI d H }|dr|d  d| S d S )NzPage.navigate)rZ   r$  Z	errorTextz at )r   rL   rg   )re   rZ   r$  r-   rQ   rQ   rR   r  J  s
   
zPage._navigatec                    s4   t ||}t| || jdI dH d }|S )zVReload this page.

        Available options are same as :meth:`goto` method.
        Page.reloadNr   )r   rM   rN   waitForNavigationr   rL   )re   r   r   r-   rQ   rQ   rR   reloadP  s   
$r'  c           
         s   t ||}| jj}|du rtd|d| j}t| j|||}i  t| j	t
jj fdd}| I dH }t|g |d   }|rJ| | jd}	|	S )a.  Wait for navigation.

        Available options are same as :meth:`goto` method.

        This returns :class:`~pyppeteer.network_manager.Response` when the page
        navigates to a new URL or reloads. It is useful for when you run code
        which will indirectly cause the page to navigate. In case of navigation
        to a different anchor or navigation due to
        `History API <https://developer.mozilla.org/en-US/docs/Web/API/History_API>`_
        usage, the navigation will return ``None``.

        Consider this example:

        .. code::

            navigationPromise = async.ensure_future(page.waitForNavigation())
            await page.click('a.my-link')  # indirectly cause a navigation
            await navigationPromise  # wait until navigation finishes

        or,

        .. code::

            await asyncio.wait([
                page.click('a.my-link'),
                page.waitForNavigation(),
            ])

        .. note::
            Usage of the History API to change the URL is considered a
            navigation.
        Nr  r   c                    s     | j| S rk   )__setitem__rZ   r-   	responsesrQ   rR   rm     rp   z(Page.waitForNavigation.<locals>.<lambda>r   )r   r   r   r   rg   r   r   r   r  r   r   ra   r   r   r"  r#  rw   rZ   )
re   r   r   r   r   r%  Zlistenerr  r+   r-   rQ   r,  rR   r(  Y  s(   
!
zPage.waitForNavigationurlOrPredicatec                    P   t ||}|dd}dtdtf fdd}t| jtjj||| j	j
I dH S )a'  Wait for request.

        :arg urlOrPredicate: A URL or function to wait for.

        This method accepts below options:

        * ``timeout`` (int|float): Maximum wait time in milliseconds, defaults
          to 30 seconds, pass ``0`` to disable the timeout.

        Example:

        .. code::

            firstRequest = await page.waitForRequest('http://example.com/resource')
            finalRequest = await page.waitForRequest(lambda req: req.url == 'http://example.com' and req.method == 'GET')
            return firstRequest.url
        r   rT   r,   rH   c                    ,   t  tr
 | jkS t rt | S dS NF
isinstancer   rZ   callablebool)r,   r.  rQ   rR   	predicate  
   

z&Page.waitForRequest.<locals>.predicateN)r   rg   r   r5  r   waitForEventr   r   ra   r   r   re   r.  r   r   r   r7  rQ   r6  rR   waitForRequest     

zPage.waitForRequestc                    r/  )a*  Wait for response.

        :arg urlOrPredicate: A URL or function to wait for.

        This method accepts below options:

        * ``timeout`` (int|float): Maximum wait time in milliseconds, defaults
          to 30 seconds, pass ``0`` to disable the timeout.

        Example:

        .. code::

            firstResponse = await page.waitForResponse('http://example.com/resource')
            finalResponse = await page.waitForResponse(lambda res: res.url == 'http://example.com' and res.status == 200)
            return finalResponse.ok
        r   rT   r-   rH   c                    r0  r1  r2  r+  r6  rQ   rR   r7    r8  z'Page.waitForResponse.<locals>.predicateN)r   rg   r   r5  r   r9  r   r   ra   r   r   r:  rQ   r6  rR   waitForResponse  r<  zPage.waitForResponsec                       t ||}| d|I dH S )zNavigate to the previous page in history.

        Available options are same as :meth:`goto` method.

        If cannot go back, return ``None``.
        Nr   _gore   r   r   rQ   rQ   rR   goBack     
zPage.goBackc                    r>  )zNavigate to the next page in history.

        Available options are same as :meth:`goto` method.

        If cannot go forward, return ``None``.
           Nr@  rB  rQ   rQ   rR   	goForward  rD  zPage.goForwarddeltac              
      s|   | j dI d H }|dd| }|dg }t||kr d S || }t| || j dd|diI d H d }|S )NzPage.getNavigationHistoryZcurrentIndexr   entrieszPage.navigateToHistoryEntryZentryIdid)r   rL   rg   lenrM   rN   r(  )re   rG  r   history_countrH  r   r-   rQ   rQ   rR   rA    s   zPage._goc                    s   | j dI dH  dS )z#Bring page to front (activate tab).Page.bringToFrontNr   rL   rh   rQ   rQ   rR   bringToFront  r   rM  c                    s@   t ||}| |di I dH  | |ddI dH  dS )a  Emulate given device metrics and user agent.

        This method is a shortcut for calling two methods:

        * :meth:`setUserAgent`
        * :meth:`setViewport`

        ``options`` is a dictionary containing these fields:

        * ``viewport`` (dict)

          * ``width`` (int): page width in pixels.
          * ``height`` (int): page width in pixels.
          * ``deviceScaleFactor`` (float): Specify device scale factor (can be
            thought as dpr). Defaults to 1.
          * ``isMobile`` (bool): Whether the ``meta viewport`` tag is taken
            into account. Defaults to ``False``.
          * ``hasTouch`` (bool): Specifies if viewport supports touch events.
            Defaults to ``False``.
          * ``isLandscape`` (bool): Specifies if viewport is in landscape mode.
            Defaults to ``False``.

        * ``userAgent`` (str): user agent string.
        viewportNr  r   )r   rO   rg   r  rB  rQ   rQ   rR   emulate  s   
zPage.emulatec                    s4   | j |krdS || _ | jdd| iI dH  dS )zSet JavaScript enable/disable.Nz$Emulation.setScriptExecutionDisabledr   )r   r   rL   r   rQ   rQ   rR   setJavaScriptEnabled  s
   
zPage.setJavaScriptEnabledc                    s   | j dd|iI dH  dS )a#  Toggles bypassing page's Content-Security-Policy.

        .. note::
            CSP bypassing happens at the moment of CSP initialization rather
            then evaluation. Usually this means that ``page.setBypassCSP``
            should be called before navigating to the domain.
        Page.setBypassCSPrJ   NrN  r   rQ   rQ   rR   setBypassCSP   s   rS  	mediaTypec                    s8   |dvrt d| | jdd|pdiI dH  dS )a5  Emulate css media type of the page.

        :arg str mediaType: Changes the CSS media type of the page. The only
                            allowed values are ``'screen'``, ``'print'``, and
                            ``None``. Passing ``None`` disables media
                            emulation.
        )screenprintNr   zUnsupported media type: zEmulation.setEmulatedMediaZmediar   N)
ValueErrorr   rL   )re   rU  rQ   rQ   rR   emulateMedia*  s    zPage.emulateMediarP  c                    s4   | j |I dH }|| _|r|  I dH  dS dS )a  Set viewport.

        Available options are:
            * ``width`` (int): page width in pixel.
            * ``height`` (int): page height in pixel.
            * ``deviceScaleFactor`` (float): Default to 1.0.
            * ``isMobile`` (bool): Default to ``False``.
            * ``hasTouch`` (bool): Default to ``False``.
            * ``isLandscape`` (bool): Default to ``False``.
        N)r   ZemulateViewportr   r)  )re   rP  ZneedsReloadrQ   rQ   rR   rO   6  s   zPage.setViewportc                 C   r   )zuGet viewport as a dictionary or None.

        Fields of returned dictionary is same as :meth:`setViewport`.
        )r   rh   rQ   rQ   rR   rP  F  s   zPage.viewportFr   r   c                   s6   | j }|du rtd|j|g|R d|iI dH S )a  Execute js-function or js-expression on browser and get result.

        :arg str pageFunction: String of js-function/expression to be executed
                               on the browser.
        :arg bool force_expr: If True, evaluate `pageFunction` as expression.
                              If False (default), try to automatically detect
                              function or expression.

        note: ``force_expr`` option is a keyword only argument.
        Nr  r   )r   r   r   )re   r   r   r   r   rQ   rQ   rR   r   N  s
   zPage.evaluatec                    s0   t j|g|R  }| jdd|iI dH  dS )aA  Add a JavaScript function to the document.

        This function would be invoked in one of the following scenarios:

        * whenever the page is navigated
        * whenever the child frame is attached or navigated. In this case, the
          function is invoked in the context of the newly attached frame.
        r   r   N)r   r   r   rL   )re   r   r   r   rQ   rQ   rR   evaluateOnNewDocument^  s   	zPage.evaluateOnNewDocumentTc                    s    | j dd| iI dH  dS )zXEnable/Disable cache for each request.

        By default, caching is enabled.
        zNetwork.setCacheDisabledZcacheDisabledNrN  r   rQ   rQ   rR   setCacheEnabledj  s   zPage.setCacheEnabledc                    s   t ||}d}d|v r|d }|dvrtd| n"d|v r>t|d \}}|dkr0d}n|dkr7d	}ntd
| |sBd}| ||I dH S )a  Take a screen shot.

        The following options are available:

        * ``path`` (str): The file path to save the image to. The screenshot
          type will be inferred from the file extension.
        * ``type`` (str): Specify screenshot type, can be either ``jpeg`` or
          ``png``. Defaults to ``png``.
        * ``quality`` (int): The quality of the image, between 0-100. Not
          applicable to ``png`` image.
        * ``fullPage`` (bool): When true, take a screenshot of the full
          scrollable page. Defaults to ``False``.
        * ``clip`` (dict): An object which specifies clipping region of the
          page. This option should have the following fields:

          * ``x`` (int): x-coordinate of top-left corner of clip area.
          * ``y`` (int): y-coordinate of top-left corner of clip area.
          * ``width`` (int): width of clipping area.
          * ``height`` (int): height of clipping area.

        * ``omitBackground`` (bool): Hide default white background and allow
          capturing screenshot with transparency.
        * ``encoding`` (str): The encoding of the image, can be either
          ``'base64'`` or ``'binary'``. Defaults to ``'binary'``.
        NrW   )pngjpegzUnknown type value: pathz	image/pngr\  z
image/jpegr]  z"Unsupported screenshot mime type: )r   rX  	mimetypes
guess_type_screenshotTask)re   r   r   ZscreenshotTypeZmimeType_rQ   rQ   rR   
screenshotq  s$   
zPage.screenshotformatc              	      s:  | j dd| jjiI d H  |d|d}}|r d|d< |dr| j dI d H }t|d	 d
 }t|d	 d }tdd||dd}| jd urd| jdd}| jdd}	| jdd}
nd}d}	d}
|
rstddd}ntddd}| j d||||	|dI d H  |dr| j dddddddiI d H  d|i}|r||d< |dkr|d ur||d< | j d|I d H }|dr| j dI d H  |dr| jd ur| 	| jI d H  |dd kr|d!d"}n	t
|d!d"}|d#}|rt|d$}|| W d    |S 1 sw   Y  |S )%NzTarget.activateTargettargetIdclipqualityrE  scaleZfullPagezPage.getLayoutMetricsZcontentSizer;   r<   r   )xyr;   r<   rh  ZisMobileFdeviceScaleFactorZisLandscapeZ   ZlandscapePrimary)ZanglerW   ZportraitPrimaryz"Emulation.setDeviceMetricsOverride)mobiler;   r<   rk  screenOrientationZomitBackgroundz+Emulation.setDefaultBackgroundColorOverridecolor)rgbard  r]  zPage.captureScreenshotencodingbase64data    r^  wb)r   rL   r   	_targetIdrg   mathceilr   r   rO   ru  	b64decodeopenwrite)re   rd  r   rf  rg  r6   r;   r<   rm  rk  	landscapern  optr  buffer_pathfrQ   rQ   rR   ra    sl   







zPage._screenshotTaskc                    s  t ||}|dd}t|d}|dd}|dd}t|d}t|d}|d	d}	d
}
d}d|v rXtj|d  }|sOtd|d  |d }
|d }nt|dp`|
}
t|dpi|}|di }t|dpxd}t|dpd}t|dpd}t|dpd}|dd}| j	dt
|||||||
||||||	|dI dH }t|dd}d|v rt|d d}|| W d   |S 1 sw   Y  |S )aG  Generate a pdf of the page.

        Options:

        * ``path`` (str): The file path to save the PDF.
        * ``scale`` (float): Scale of the webpage rendering, defaults to ``1``.
        * ``displayHeaderFooter`` (bool): Display header and footer.
          Defaults to ``False``.
        * ``headerTemplate`` (str): HTML template for the print header. Should
          be valid HTML markup with following classes.

          * ``date``: formatted print date
          * ``title``: document title
          * ``url``: document location
          * ``pageNumber``: current page number
          * ``totalPages``: total pages in the document

        * ``footerTemplate`` (str): HTML template for the print footer. Should
          use the same template as ``headerTemplate``.
        * ``printBackground`` (bool): Print background graphics. Defaults to
          ``False``.
        * ``landscape`` (bool): Paper orientation. Defaults to ``False``.
        * ``pageRanges`` (string): Paper ranges to print, e.g., '1-5,8,11-13'.
          Defaults to empty string, which means all pages.
        * ``format`` (str): Paper format. If set, takes priority over
          ``width`` or ``height``. Defaults to ``Letter``.
        * ``width`` (str): Paper width, accepts values labeled with units.
        * ``height`` (str): Paper height, accepts values labeled with units.
        * ``margin`` (dict): Paper margins, defaults to ``None``.

          * ``top`` (str): Top margin, accepts values labeled with units.
          * ``right`` (str): Right margin, accepts values labeled with units.
          * ``bottom`` (str): Bottom margin, accepts values labeled with units.
          * ``left`` (str): Left margin, accepts values labeled with units.

        * ``preferCSSPageSize``: Give any CSS ``@page`` size declared in the
          page priority over what is declared in ``width`` and ``height`` or
          ``format`` options. Defaults to ``False``, which will scale the
          content to fit the paper size.

        :return: Return generated PDF ``bytes`` object.

        .. note::
            Generating a pdf is currently only supported in headless mode.

        :meth:`pdf` generates a pdf of the page with ``print`` css media. To
        generate a pdf with ``screen`` media, call
        ``page.emulateMedia('screen')`` before calling :meth:`pdf`.

        .. note::
            By default, :meth:`pdf` generates a pdf with modified colors for
            printing. Use the ``--webkit-print-color-adjust`` property to force
            rendering of exact colors.

        .. code::

            await page.emulateMedia('screen')
            await page.pdf({'path': 'page.pdf'})

        The ``width``, ``height``, and ``margin`` options accept values labeled
        with units. Unlabeled values are treated as pixels.

        A few examples:

        - ``page.pdf({'width': 100})``: prints with width set to 100 pixels.
        - ``page.pdf({'width': '100px'})``: prints with width set to 100 pixels.
        - ``page.pdf({'width': '10cm'})``: prints with width set to 100 centimeters.

        All available units are:

        - ``px``: pixel
        - ``in``: inch
        - ``cm``: centimeter
        - ``mm``: millimeter

        The format options are:

        - ``Letter``: 8.5in x 11in
        - ``Legal``: 8.5in x 14in
        - ``Tabloid``: 11in x 17in
        - ``Ledger``: 17in x 11in
        - ``A0``: 33.1in x 46.8in
        - ``A1``: 23.4in x 33.1in
        - ``A2``: 16.5in x 23.4in
        - ``A3``: 11.7in x 16.5in
        - ``A4``: 8.27in x 11.7in
        - ``A5``: 5.83in x 8.27in
        - ``A6``: 4.13in x 5.83in

        .. note::
            ``headerTemplate`` and ``footerTemplate`` markup have the following
            limitations:

            1. Script tags inside templates are not evaluated.
            2. Page styles are not visible inside templates.
        rh  rE  displayHeaderFooterheaderTemplater   footerTemplateprintBackgroundr  
pageRangesr9   g      &@rd  zUnknown paper format: r;   r<   margintopr   leftbottomrightpreferCSSPageSizeFzPage.printToPDF)r  r  r  r  r  rh  
paperWidthpaperHeight	marginTopmarginBottom
marginLeftmarginRightr  r  Nrv  rw  r^  rx  )r   rg   r5  r#   rB   lowerrX  convertPrintParameterToInchesr   rL   r   ru  r|  r}  r~  )re   r   r   rh  r  r  r  r  r  r  r  r  fmtZmarginOptionsr  r  r  r  r  r  r  r  rQ   rQ   rR   pdf  sh   
a


zPage.pdfc                    s   t d | dI dH S )z,[Deprecated] Get page content as plain text.z`Page.plainText` is deprecated.z() => document.body.innerTextN)r\   warningr   rh   rQ   rQ   rR   	plainTextv  s   
zPage.plainTextc                    s"   | j }|s
td| I dH S )zGet page's title.r   N)r   r   r  r  rQ   rQ   rR   r  {  s
   z
Page.titlec                    sx   t ||}| jj}|du rtdt|d}|r&| jdI dH  dS |dd| jjiI dH  | jj	I dH  dS )a  Close this page.

        Available options:

        * ``runBeforeUnload`` (bool): Defaults to ``False``. Whether to run the
          `before unload <https://developer.mozilla.org/en-US/docs/Web/Events/beforeunload>`_
          page handlers.

        By defaults, :meth:`close` **does not** run beforeunload handlers.

        .. note::
           If ``runBeforeUnload`` is passed as ``True``, a ``beforeunload``
           dialog might be summoned and should be handled manually via page's
           ``dialog`` event.
        NzHProtocol Error: Connection Closed. Most likely the page has been closed.runBeforeUnload
Page.closezTarget.closeTargetre  )
r   r   _connectionr   r5  rg   rL   r   ry  r   )re   r   r   connr  rQ   rQ   rR   r%     s   
r  c                 C   r   )z'Indicate that the page has been closed.)r|   rh   rQ   rQ   rR   isClosed  s   zPage.isClosedc                 C   r   )z+Get :class:`~pyppeteer.input.Mouse` object.)r   rh   rQ   rQ   rR   mouse  r   z
Page.mousec                    s6   | j }|du rtd|j||fi |I dH  dS )a0  Click element which matches ``selector``.

        This method fetches an element with ``selector``, scrolls it into view
        if needed, and then uses :attr:`mouse` to click in the center of the
        element. If there's no element matching ``selector``, the method raises
        ``PageError``.

        Available options are:

        * ``button`` (str): ``left``, ``right``, or ``middle``, defaults to
          ``left``.
        * ``clickCount`` (int): defaults to 1.
        * ``delay`` (int|float): Time to wait between ``mousedown`` and
          ``mouseup`` in milliseconds. defaults to 0.

        .. note:: If this method triggers a navigation event and there's a
            separate :meth:`waitForNavigation`, you may end up with a race
            condition that yields unexpected results. The correct pattern for
            click and wait for navigation is the following::

                await asyncio.gather(
                    page.waitForNavigation(waitOptions),
                    page.click(selector, clickOptions),
                )
        Nr  )r   r   clickre   r   r   r   r   rQ   rQ   rR   r    s
   z
Page.clickc                    r   )zMouse hover the element which matches ``selector``.

        If no element matched the ``selector``, raise ``PageError``.
        Nr  )r   r   hoverr   rQ   rQ   rR   r    r   z
Page.hoverc                    r   )z|Focus the element which matches ``selector``.

        If no element matched the ``selector``, raise ``PageError``.
        Nr  )r   r   focusr   rQ   rQ   rR   r    r   z
Page.focusr   c                    s,   | j }|s
td|j|g|R  I dH S )zSelect options and return selected values.

        If no element matched the ``selector``, raise ``ElementHandleError``.
        r   N)r   r   select)re   r   r   r   rQ   rQ   rR   r    s
   zPage.selectr   c                    s0   | j }|s
td|j|||fi |I dH S )zType ``text`` on the element which matches ``selector``.

        If no element matched the ``selector``, raise ``PageError``.

        Details see :meth:`pyppeteer.input.Keyboard.type`.
        r   N)r   r   rW   )re   r   r   r   r   r   rQ   rQ   rR   rW     s
   z	Page.typeselectorOrFunctionOrTimeoutc                 O   ,   | j }|s	td|j||g|R i |S )aV  Wait for function, timeout, or element which matches on page.

        This method behaves differently with respect to the first argument:

        * If ``selectorOrFunctionOrTimeout`` is number (int or float), then it
          is treated as a timeout in milliseconds and this returns future which
          will be done after the timeout.
        * If ``selectorOrFunctionOrTimeout`` is a string of JavaScript
          function, this method is a shortcut to :meth:`waitForFunction`.
        * If ``selectorOrFunctionOrTimeout`` is a selector string or xpath
          string, this method is a shortcut to :meth:`waitForSelector` or
          :meth:`waitForXPath`. If the string starts with ``//``, the string is
          treated as xpath.

        Pyppeteer tries to automatically detect function or selector, but
        sometimes miss-detects. If not work as you expected, use
        :meth:`waitForFunction` or :meth:`waitForSelector` directly.

        :arg selectorOrFunctionOrTimeout: A selector, xpath, or function
                                          string, or timeout (milliseconds).
        :arg Any args: Arguments to pass the function.
        :return: Return awaitable object which resolves to a JSHandle of the
                 success value.

        Available options: see :meth:`waitForFunction` or
        :meth:`waitForSelector`
        r   )r   r   waitFor)re   r  r   r   r   r   rQ   rQ   rR   r    s   zPage.waitForc                 K   &   | j }|s	td|j||fi |S )a  Wait until element which matches ``selector`` appears on page.

        Wait for the ``selector`` to appear in page. If at the moment of
        calling the method the ``selector`` already exists, the method will
        return immediately. If the selector doesn't appear after the
        ``timeout`` milliseconds of waiting, the function will raise error.

        :arg str selector: A selector of an element to wait for.
        :return: Return awaitable object which resolves when element specified
                 by selector string is added to DOM.

        This method accepts the following options:

        * ``visible`` (bool): Wait for element to be present in DOM and to be
          visible; i.e. to not have ``display: none`` or ``visibility: hidden``
          CSS properties. Defaults to ``False``.
        * ``hidden`` (bool): Wait for element to not be found in the DOM or to
          be hidden, i.e. have ``display: none`` or ``visibility: hidden`` CSS
          properties. Defaults to ``False``.
        * ``timeout`` (int|float): Maximum time to wait for in milliseconds.
          Defaults to 30000 (30 seconds). Pass ``0`` to disable timeout.
        r   )r   r   waitForSelectorr  rQ   rQ   rR   r    s   zPage.waitForSelectorr   c                 K   r  )ap  Wait until element which matches ``xpath`` appears on page.

        Wait for the ``xpath`` to appear in page. If the moment of calling the
        method the ``xpath`` already exists, the method will return
        immediately. If the xpath doesn't appear after ``timeout`` milliseconds
        of waiting, the function will raise exception.


        :arg str xpath: A [xpath] of an element to wait for.
        :return: Return awaitable object which resolves when element specified
                 by xpath string is added to DOM.

        Available options are:

        * ``visible`` (bool): wait for element to be present in DOM and to be
          visible, i.e. to not have ``display: none`` or ``visibility: hidden``
          CSS properties. Defaults to ``False``.
        * ``hidden`` (bool): wait for element to not be found in the DOM or to
          be hidden, i.e. have ``display: none`` or ``visibility: hidden`` CSS
          properties. Defaults to ``False``.
        * ``timeout`` (int|float): maximum time to wait for in milliseconds.
          Defaults to 30000 (30 seconds). Pass ``0`` to disable timeout.
        r   )r   r   waitForXPath)re   r   r   r   r   rQ   rQ   rR   r  .  s   zPage.waitForXPathc                 O   r  )a  Wait until the function completes and returns a truthy value.

        :arg Any args: Arguments to pass to ``pageFunction``.
        :return: Return awaitable object which resolves when the
                 ``pageFunction`` returns a truthy value. It resolves to a
                 :class:`~pyppeteer.execution_context.JSHandle` of the truthy
                 value.

        This method accepts the following options:

        * ``polling`` (str|number): An interval at which the ``pageFunction``
          is executed, defaults to ``raf``. If ``polling`` is a number, then
          it is treated as an interval in milliseconds at which the function
          would be executed. If ``polling`` is a string, then it can be one of
          the following values:

          * ``raf``: to constantly execute ``pageFunction`` in
            ``requestAnimationFrame`` callback. This is the tightest polling
            mode which is suitable to observe styling changes.
          * ``mutation``: to execute ``pageFunction`` on every DOM mutation.

        * ``timeout`` (int|float): maximum time to wait for in milliseconds.
          Defaults to 30000 (30 seconds). Pass ``0`` to disable timeout.
        r   )r   r   waitForFunction)re   r   r   r   r   r   rQ   rQ   rR   r  K  s   zPage.waitForFunctionrQ   rk   )rH   r"   )rH   r!   )rH   r   )rH   N)T){__name__
__module____qualname____doc__r   ra   r   rB   r   r   float__annotations__staticmethodr   r5  r	   r   rS   r   propertyrD   r   r   rx   rz   r   r   r   r   r   r   r   r   r   r   r   r    r   r   r   intr   r   r   r   r   r   r   r   r   r   r   r   JZJevalZJJZJJevalZJxr
   r   r   r   r   r   r   r   r   r   r   r  r6   ry   r  r^   rr   rt   r]   ru   rZ   r  r  r   r&  r  r)  r(  r   r;  r=  rC  rF  rA  rO  rQ  rR  rT  rY  rO   rP  r   rZ  r[  bytesrc  ra  r  r  r  r%   r  r   r  r  r  r  r  rW   r   r  r  r  r  __classcell__rQ   rQ   r   rR   r#   (   s  
 
	
!U
#(!
,
"
E	7
#
"


 ",C 

&
"#$.r#   )	TimestampZ	DocumentsZFramesZJSEventListenersZNodesZLayoutCountZRecalcStyleCountZLayoutDurationZRecalcStyleDurationZScriptDurationZTaskDurationZJSHeapUsedSizeZJSHeapTotalSizerE  `   gfffffB@g=
ףp=@)pxincmmm	parameterrH   c                 C   s   | du rdS t | ttfr| }|d S t | trO| }|dd  }|tv r-|dd }nd}|}zt|}W n tyD   td| w |t|  }|d S tdtt|  )z"Convert print parameter to inches.Nr  z!Failed to parse parameter value: z)page.pdf() Cannot handle parameter type: r  )	r3  r  r  r   r  unitToPixelsrX  	TypeErrorrW   )r  Zpixelsr   unitZ	valueTextr   rQ   rQ   rR   r  ~  s(   
r  c                	   @   sj   e Zd ZdZddededee ddfddZedefd	d
Z	edefddZ
edee fddZdS )r   ziConsole message class.

    ConsoleMessage objects are dispatched by page via the ``console`` event.
    NrW   r   r   rH   c                 C   s(   || _ || _|d ur|| _d S g | _d S rk   )r  _text_args)re   rW   r   r   rQ   rQ   rR   r     s   zConsoleMessage.__init__c                 C   r   )zReturn type of this message.)r  rh   rQ   rQ   rR   rW     r   zConsoleMessage.typec                 C   r   )z+Return text representation of this message.)r  rh   rQ   rQ   rR   r     r   zConsoleMessage.textc                 C   r   )z/Return list of args (JSHandle) of this message.)r  rh   rQ   rQ   rR   r     r   zConsoleMessage.argsrk   )r  r  r  r  r   r   r   r   r  rW   r   r   rQ   rQ   rQ   rR   r     s     r   )Hr  rM   ru  r  loggingrz  r_  typesr   typingr   r   r   r   r   r   r	   r
   Zpyeer   Z	pyppeteerr   Zpyppeteer.connectionr   Zpyppeteer.coverager   Zpyppeteer.dialogr   Zpyppeteer.element_handler   Zpyppeteer.emulation_managerr   Zpyppeteer.errorsr   Zpyppeteer.execution_contextr   Zpyppeteer.frame_managerr   r   Zpyppeteer.helperr   Zpyppeteer.inputr   r   r   Zpyppeteer.navigator_watcherr   Zpyppeteer.network_managerr   r   r   Zpyppeteer.tracingr   Zpyppeteer.utilr   Zpyppeteer.workerr    Zpyppeteer.browserr!   r"   	getLoggerr  r\   r#   r  r  r  r  r   r  objectr   rQ   rQ   rQ   rR   <module>   s^   (
            N"