
    &th                       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
rddl9m:Z:m;Z;  ej<        e=          Z> G d de          Z?dZ@dddddZAd edeBeCeDf         d!eeC         fd"ZE G 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                   	    e Zd ZU dZ edi 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&0
  
        Zee	ee	e
f         f         ed1<   e	 dd3ed4d5d6ed7ee         d8ed9d fd:            Z	 dd3ed4d5d;ed6ed8ed9d2f fd<Zedd=            Zedd?            Zd@edAed9d2fdBZdCed9d2fdDZed9edE         fdF            Zed9efdG            Zed9efdH            Zed9efdI            ZdJe	d9d2fdKZ eddM            Z!ed9e"dE         fdN            Z#ed9e"e$         fdO            Z%dPed9d2fdQZ&dRed9d2fdSZ'dTe(d9d2fdUZ)dVe	dWed9d2fdXZ*dCed9d2fdYZ+dJe	d9ee,         fdZZ-d[e	d@ed9e.fd\Z/d]e.d9e.fd^Z0dJe	d[e	d@ed9efd_Z1dJe	d[e	d@ed9efd`Z2dJe	d9e"e,         fdaZ3dbe	d9e"e,         fdcZ4e-Z5e1Z6e3Z7e2Z8e4Z9dde	d9e"ee	e:e	e(ef         f                  fdeZ;dfed9d2fdgZ<dfed9d2fdhZ=ddiedAe	d9e,fdjZ>ddiedAe	d9e,fdkZ?dle	d9e	fdmZ@dne	doeAdpef         d9d2fdqZBdree	e	f         d9efdsZCdtee	e	f         d9d2fduZDdve	d9d2fdwZEd9ee	ef         fdxZFdCed9d2fdyZGde"d9ee	ef         fdzZHd{ed9d2fd|ZIdCed9d2fd}ZJdCed9d2fd~ZKde	d@e"e.         d9d2fdZLdCed9d2fdZMed9e	fd            ZNd9e	fdZOde	d9d2fdZPdde	diedAed9eeQ         fdZRde	de	d9ee	         fdZSddiedAed9eeQ         fdZTddiedAed9eeQ         fdZU	 dde:e	eAeVgef         f         diedAed9eVfdZW	 dde:e	eAeQgef         f         diedAed9eQfdZXddiedAed9eeQ         fdZYddiedAed9eeQ         fdZZde(died9eeQ         fdZ[ddZ\ddiedAed9d2fdZ]dRed9d2fdZ^dRed9d2fdZ_dde	d9d2fdZ`ded9d2fdZaed9ee         fd            Zbddd[e	d@eded9efdZcd[e	d@e	d9d2fdZdddRed9d2fdZeddiedAed9e:efe	f         fdZgde	died9e:efe	f         fdZhddiedAed9effdZid9e	fdZjd9e	fdZkddiedAed9d2fdZld9efdZmed9enfd            ZoddJe	diedAed9d2fdZpdJe	d9d2fdZqdJe	d9d2fdZrdJe	de	d9e"e	         fdZsddJe	de	diedAed9d2f
dZt	 dde:e	e(e
f         died@edAed9euf
dZvddJe	diedAed9eufdZwdde	diedAed9eufdZxdd[e	died@e	dAed9euf
dZy x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DOMContentLoadeddomcontentloadedErrorerrorr   	pageerrorr   requestr   responseRequestFailedrequestfailedRequestFinishedrequestfinishedFrameAttachedframeattachedFrameDetachedframedetachedFrameNavigatedframenavigatedLoadloadMetricsmetricsWorkerCreatedworkercreatedWorkerDestroyedworkerdestroyed      !@   )widthheight      ǧ@@gffffffG@gffffff7@g     0@gffffff'@g
ףp= @gRQ@)
letterlegaltabloidledgera0a1a2a3a4a5PaperFormatsNclienttargetr#   ignoreHTTPSErrorsdefaultViewportscreenshotTaskQueuereturnc                   K   |                      d           d{V  |                      d           d{V d         }t          | ||||          }t          j        |                      dddd          |                      d	d
di          |                      di           |                      di           |                      di           |                      di           |                      di                      d{V  |r|                      dddi           d{V  |r|                    |           d{V  |S )z+Async function which makes new page object.zPage.enableNzPage.getFrameTree	frameTreezTarget.setAutoAttachTF)
autoAttachwaitForDebuggerOnStartzPage.setLifecycleEventsEnabledenabledzNetwork.enablezRuntime.enablezSecurity.enablezPerformance.enablez
Log.enablez#Security.setIgnoreCertificateErrorsignore)sendr%   asynciogathersetViewport)rU   rV   rW   rX   rY   r\   pages          b/var/www/html/mycamper/aliexpress-site/backend/venv/lib/python3.11/site-packages/pyppeteer/page.pycreatezPage.createU   s      kk-(((((((((!;;':;;;;;;;;[I	FFI/@BUVVnKK.t_d0e0effKK89d:KLLKK("--KK("--KK)2..KK,b11KKb))
 
 	
 	
 	
 	
 	
 	
 	
  	W++ChPTEUVVVVVVVVV 	4""?333333333    r\   c                 \    t                                                       d _         _        | _        t                     _        t           j                   _        t           j                   _
        t          |            _        t           j                   _        t                     _        t#                     _        i  _        | _        d _        d _        t/                     _        d  _        |g }| _        i  _        dt8          dd f fd}dt8          dd f fd}                    d|                               d	|            j        }|                    t          j        j         fd
           |                    t          j        j          fd           |                    t          j        j!         fd            j        }	|	                    t          j        j"         fd           |	                    t          j        j#         fd           |	                    t          j        j$         fd           |	                    t          j        j%         fd                               d fd                               d fd                               d fd                               d fd                               d fd                               d fd                               d fd                               d fd                                d! fd"           d#tL          j'        j(        dd f fd$}
 j        j)        *                    |
           d S )%NF0u  TeventrZ   c                    | d         }|d         dk    rN	                      dd| d         i           n,# t          $ r}t          t          |           Y d }~nd }~ww xY wd S | d         }                    |d         |          }t          ||d         j        j                  }|j        |<   	                    t          j        j        |           d S )N
targetInfotypeworkerzTarget.detachFromTarget	sessionIdurl)ra   	Exceptionr   logger_createSessionr!   _addConsoleMessage_handleException_workersemitr%   Eventsr@   )rk   rm   erp   sessionro   rU   selfs         rf   _onTargetAttachedz(Page.__init__.<locals>._onTargetAttached   s    |,J&!X--*KK 9K{I[;]^^^^  * * *vq))))))))*k*I++Jv,>	JJGGZ%68OQUQfhhF'-DM)$IIdk/88888s   6 
A AAc                     | d         }j                             |          }|d S                     t          j        j        |           j         |= d S )Nrp   )rw   getrx   r%   ry   rB   )rk   rp   ro   r|   s      rf   _onTargetDetachedz(Page.__init__.<locals>._onTargetDetached   sU    k*I]&&y11F~IIdk16:::i(((rh   zTarget.attachedToTargetzTarget.detachedFromTargetc                 N                         t          j        j        |           S N)rx   r%   ry   r6   rk   r|   s    rf   <lambda>zPage.__init__.<locals>.<lambda>       		$+Jcej@k@k rh   c                 N                         t          j        j        |           S r   )rx   r%   ry   r8   r   s    rf   r   zPage.__init__.<locals>.<lambda>   r   rh   c                 N                         t          j        j        |           S r   )rx   r%   ry   r:   r   s    rf   r   zPage.__init__.<locals>.<lambda>   s    4;KeglAmAm rh   c                 N                         t          j        j        |           S r   )rx   r%   ry   r   r   s    rf   r   zPage.__init__.<locals>.<lambda>   s    DIIdkFY[`<a<a rh   c                 N                         t          j        j        |           S r   )rx   r%   ry   r   r   s    rf   r   zPage.__init__.<locals>.<lambda>   s    TYYt{G[]b=c=c rh   c                 N                         t          j        j        |           S r   )rx   r%   ry   r2   r   s    rf   r   zPage.__init__.<locals>.<lambda>   s    $))DKLeglBmBm rh   c                 N                         t          j        j        |           S r   )rx   r%   ry   r4   r   s    rf   r   zPage.__init__.<locals>.<lambda>   s    DIIdkNikpDqDq rh   zPage.domContentEventFiredc                 L                         t          j        j                  S r   )rx   r%   ry   r+   r   s    rf   r   zPage.__init__.<locals>.<lambda>   s    TYYt{Gc=d=d rh   zPage.loadEventFiredc                 L                         t          j        j                  S r   )rx   r%   ry   r<   r   s    rf   r   zPage.__init__.<locals>.<lambda>   s    tyyAQ7R7R rh   zRuntime.consoleAPICalledc                 .                         |           S r   )_onConsoleAPIr   s    rf   r   zPage.__init__.<locals>.<lambda>   s    D<N<Nu<U<U rh   zRuntime.bindingCalledc                 .                         |           S r   )_onBindingCalledr   s    rf   r   zPage.__init__.<locals>.<lambda>   s    9N9Nu9U9U rh   zPage.javascriptDialogOpeningc                 .                         |           S r   )	_onDialogr   s    rf   r   zPage.__init__.<locals>.<lambda>   s    u@U@U rh   zRuntime.exceptionThrownc                 T                         |                     d                    S )NexceptionDetails)rv   r   )	exceptionr|   s    rf   r   zPage.__init__.<locals>.<lambda>   s%    t?T?TU^UbUbcuUvUv?w?w rh   zInspector.targetCrashedc                 ,                                     S r   )_onTargetCrashedr   s    rf   r   zPage.__init__.<locals>.<lambda>   s    4;P;P;R;R rh   zPerformance.metricsc                 .                         |           S r   )_emitMetricsr   s    rf   r   zPage.__init__.<locals>.<lambda>   s    t7H7H7O7O rh   zLog.entryAddedc                 .                         |           S r   )_onLogEntryAddedr   s    rf   r   zPage.__init__.<locals>.<lambda>   s    $2G2G2N2N rh   futc                 ^                         t          j        j                   d_        d S )NT)rx   r%   ry   r&   _closed)r   r|   s    rf   closedzPage.__init__.<locals>.closed   s%    IIdk'(((DLLLrh   )+super__init__r   _client_targetr   	_keyboardr   _mouser   _touchscreenr   _frameManagerr   _networkManagerr   _emulationManagerr   _tracing_pageBindings_ignoreHTTPSErrors_defaultNavigationTimeout_javascriptEnabledr   	_coverage	_viewport_screenshotTaskQueuerw   r   onry   r6   r8   r:   r   r   r2   r4   rb   futuresFuture_isClosedPromiseadd_done_callback)r|   rU   rV   r\   rW   rY   r}   r   _fm_nmr   	__class__s   ``         rf   r   zPage.__init__q   s    	!&))FDN33'??)&)TBB-fd6HII!1&!9!9<>"3).&"&!&)))-&"$$7!+-	9T 	9d 	9 	9 	9 	9 	9 	9 	9	)T 	)d 	) 	) 	) 	) 	) 	) 			+->???		-/@AAA |"02k2k2k2klll|"02k2k2k2klll|"13m3m3m3mnnn"~$,.a.a.a.abbb~$-/c/c/c/cddd~$24m4m4m4mnnn~$46q6q6q6qrrr		-/d/d/d/deee		')R)R)R)RSSS		,.U.U.U.UVVV		)+U+U+U+UVVV		02U2U2U2UVVV		+-w-w-w-wxxx		+-R-R-R-RSSS		')O)O)O)OPPP		"$N$N$N$NOOO	 . 	 4 	  	  	  	  	  	  	%77?????rh   c                     | j         S )z'Return a target this page created from.)r   r|   s    rf   rV   zPage.target   s     |rh   r"   c                     | j         j        S )z$Get the browser the page belongs to.)r   browserr   s    rf   r   zPage.browser   s     |##rh   argskwargsc                 L    |                      dt          d                     d S )Nr.   zPage crashed!)rx   r   )r|   r   r   s      rf   r   zPage._onTargetCrashed   s$    		'9_5566666rh   rk   c                    |                     di           }|                     dd          }|                     dd          }|                     dg           }|                     dd          }|D ]}t          j        | j        |           |dk    r5|                     t
          j        j        t          ||                     d S d S )Nentrylevel textr   sourcero   )	r   r   releaseObjectr   rx   r%   ry   r(   ConsoleMessage)r|   rk   r   r   r   r   r   args           rf   r   zPage._onLogEntryAdded   s    		'2&&		'2&&yy$$yy$$8R(( 	4 	4C s3333XIIdk)>%+F+FGGGGG rh   r   c                     | j         j        S )z>Get main :class:`~pyppeteer.frame_manager.Frame` of this page.)r   
_mainFramer   s    rf   	mainFramezPage.mainFrame   s     !,,rh   c                     | j         S )z.Get :class:`~pyppeteer.input.Keyboard` object.)r   r   s    rf   keyboardzPage.keyboard        ~rh   c                     | j         S )z1Get :class:`~pyppeteer.input.Touchscreen` object.)r   r   s    rf   touchscreenzPage.touchscreen   s       rh   c                     | j         S )z-Return :class:`~pyppeteer.coverage.Coverage`.)r   r   s    rf   coveragezPage.coverage   r   rh   selectorc                 p   K   | j         }|t          d          |                    |           d{V  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r|   r   frames      rf   r   zPage.tap   sL      
 =O,,,ii!!!!!!!!!!!rh   r   c                     | j         S )zGet tracing object.)r   r   s    rf   tracingzPage.tracing   s     }rh   c                 N    t          | j                                                  S )zGet all frames of this page.)listr   framesr   s    rf   r   zPage.frames  s!     D&--//000rh   c                 N    t          | j                                                  S )zGet all workers of this page.)r   rw   valuesr   s    rf   workerszPage.workers  s      DM((**+++rh   valuec                 F   K   | j                             |           d{V 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)r|   r   s     rf   r   zPage.setRequestInterception  s2      B )@@GGGGGGGGGrh   r_   c                 J   K   | j                             |           d{V  dS )z Set offline mode enable/disable.N)r   setOfflineModer|   r_   s     rf   r   zPage.setOfflineMode/  s5      "11':::::::::::rh   timeoutc                     || _         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   )r|   r   s     rf   setDefaultNavigationTimeoutz Page.setDefaultNavigationTimeout3  s     *1&&&rh   methodmsgc                    K   	 | j                             ||           d {V  d S # t          $ r }t          t          |           Y d }~d S d }~ww xY wr   )r   ra   rr   r   rs   )r|   r   r   rz   s       rf   _sendz
Page._sendD  s|      	",##FC00000000000 	" 	" 	"vq!!!!!!!!!	"s   !' 
AAAc                     | j         sd S | j        j                            |                     d|                    d          dd                     d S )NzSecurity.handleCertificateErroreventIdcontinue)r   action)r   r   _loopcreate_taskr   r   r|   rk   s     rf   _onCertificateErrorzPage._onCertificateErrorJ  sa    & 	F&&JJ8eiiPYFZFZfp:q:qrr	
 	
 	
 	
 	
rh   c                 l   K   | j         }|st          d          |                    |           d{V 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   s      rf   r   zPage.querySelectorQ  sL        	.,---((222222222rh   pageFunctionc                    K   | j         st          d          | j                                          d{V }|st          d           |j        |g|R   d{V 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)r|   r   r   contexts       rf   r   zPage.evaluateHandle_  s       ~ 	.,---7799999999 	+M***+W+L@4@@@@@@@@@@rh   prototypeHandlec                    K   | j         st          d          | j                                          d{V }|st          d          |                    |           d{V 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)r|   r   r   s      rf   r  zPage.queryObjectso  s      
 ~ 	.,---7799999999 	+M***))/:::::::::rh   c                 `   K   | j         }|st          d           |j        ||g|R   d{V 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r|   r   r   r   r   s        rf   r  zPage.querySelectorEval{  sU        	.,---,U,X|KdKKKKKKKKKKrh   c                 `   K   | j         }|st          d           |j        ||g|R   d{V S )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  s        rf   r  zPage.querySelectorAllEval  sU        	.,---/U/,NNNNNNNNNNNrh   c                 l   K   | j         }|st          d          |                    |           d{V S )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   s      rf   r	  zPage.querySelectorAll  sL        	.,---++H555555555rh   
expressionc                 l   K   | j         }|st          d          |                    |           d{V S )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)r|   r
  r   s      rf   r  z
Page.xpath  sJ        	.,---[[,,,,,,,,,rh   urlsc                    K   |s| j         f}| j                            dd|i           d{V }|                    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)rq   r   ra   r   )r|   r  resps      rf   r  zPage.cookies  s[      (  	H;D\&&';fd_MMMMMMMMxx	2&&&rh   r  c                    K   | j         }|D ]^}t          di |}|                    d          s|                    d          r||d<   | j                            d|           d{V  _dS )zDelete cookie.

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

        * ``name`` (str): **required**
        * ``url`` (str)
        * ``domain`` (str)
        * ``path`` (str)
        * ``secure`` (bool)
        rq   httpzNetwork.deleteCookiesN )rq   dictr   
startswithr   ra   )r|   r  pageURLcookieitems        rf   deleteCookiezPage.deleteCookie  s       ( 	C 	CF>>&>>D::e$$ &););F)C)C &%U,##$;TBBBBBBBBBB		C 	Crh   c                 >  K   | j         }|                    d          }g }|D ]}t          di |}d|vr|r||d<   |                    d          dk    r)|                    dd          }t	          d| d          |                    dd                              d          r)|                    dd          }t	          d	| d          |                    |            | j        |  d
{V  |r%| j                            dd|i           d
{V  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  rq   zabout:blanknamer   z Blank page can not have cookie ""zdata:z#Data URL page can not have cookie "NzNetwork.setCookiesr  r  )	rq   r  r  r   r   appendr  r   ra   )r|   r  r  startsWithHTTPitemsr  r  r  s           rf   	setCookiezPage.setCookie  st      ( ++F33 
	 
	F>>&>>DD  ^ %Uxx-//xx++ J4 J J JKKKxxr""--g66 Oxx++ Md M M MNNNLLd'''''''' 	O,##$89e:MNNNNNNNNNNN	O 	Orh   optionsc                    K   | j         }|st          d          t          ||          }|                    |           d{V 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r|   r!  r   r   s       rf   r#  zPage.addScriptTag
  s[        	.,---Wf--''000000000rh   c                    K   | j         }|st          d          t          ||          }|                    |           d{V S )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$  s       rf   r&  zPage.addStyleTag  s[        	.,---Wf--&&w/////////rh   filePathc                 l   K   | j         }|st          d          |                    |           d{V S )zu[Deprecated] Inject file to this page.

        This method is deprecated. Use :meth:`addScriptTag` instead.
        r   N)r   r   
injectFile)r|   r'  r   s      rf   r)  zPage.injectFile.  sL      
  	.,---%%h/////////rh   r  pyppeteerFunction.c                   K   | j                             |          rt          d| d| d          || j         |<   d}t          j        ||          | j                            dd|i           d{V  | j                            dd	i           d{V  d
t          dt          ddfdt          j
                    t          j        fd| j        D                        d{V  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
  rZ   c                    K   	 |                      |d           d {V  d S # t          $ r }t          t          |           Y d }~d S d }~ww xY w)NT
force_expr)evaluaterr   r   rs   )r   r
  rz   s      rf   	_evaluatez&Page.exposeFunction.<locals>._evaluate\  sz      &nnZDnAAAAAAAAAAA & & &61%%%%%%%%%&s   # 
AAAc                 N    g | ]!}                      |                    "S r  )r   ).0r   r1  r
  loops     rf   
<listcomp>z'Page.exposeFunction.<locals>.<listcomp>c  s3    ddduD,,YYuj-I-IJJdddrh   )r   r   r   r   evaluationStringr   ra   r   strrb   get_event_loopwaitr   )r|   r  r*  addPageBindingr1  r
  r4  s       @@@rf   exposeFunctionzPage.exposeFunction8  sP      !!$'' 	rpDppX\pppqqq#44 $ ,^TBB
l 4vtnEEEEEEEEEl G(T^I_`````````	&5 	&c 	&d 	& 	& 	& 	& %''lddddddX\Xcdddeeeeeeeeeeerh   credentialsc                 F   K   | j                             |           d{V S )zProvide credentials for http authentication.

        ``credentials`` should be ``None`` or dict which has ``username`` and
        ``password`` field.
        N)r   authenticate)r|   r<  s     rf   r>  zPage.authenticatee  s1       )66{CCCCCCCCCrh   headersc                 F   K   | j                             |           d{V S )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)r|   r?  s     rf   rA  zPage.setExtraHTTPHeadersm  s1       )==gFFFFFFFFFrh   	userAgentc                 F   K   | j                             |           d{V S )zqSet user agent to use in this page.

        :arg str userAgent: Specific user agent to use in this page
        N)r   setUserAgent)r|   rB  s     rf   rD  zPage.setUserAgent}  s1      
 )66yAAAAAAAAArh   c                 |   K   | j                             d           d{V }|                     |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.getMetricsNr?   )r   ra   _buildMetricsObject)r|   r1   s     rf   r?   zPage.metrics  sI      0 **+CDDDDDDDD''(;<<<rh   c                     |                      t          j        j        |d         |                     |d                   d           d S )Ntitler?   )rH  r?   )rx   r%   ry   r>   rF  r   s     rf   r   zPage._emitMetrics  sM    		K5>dF^F^_den_oFpFp!r!r	
 	
 	
 	
 	
rh   c                 X    i }|pg D ]"}|d         t           v r|d         ||d         <   #|S )Nr  r   )supportedMetrics)r|   r?   resultmetrics       rf   rF  zPage._buildMetricsObject  sB    m 	9 	9Ff~!111)/vf~&rh   r   c                     t          j        |          }|                     t          j        j        t          |                     d S r   )r   getExceptionMessagerx   r%   ry   r   )r|   r   messages      rf   rv   zPage._handleException  s:    ,-=>>		$+'7););<<<<<rh   c                    |d         }| j                             |          }g }|                    dg           D ]0}|                    | j                             ||                     1|                     |d         |           d S )NexecutionContextIdr   rn   )r   executionContextByIdr   r  createJSHandleru   )r|   rk   _idr   r   r   s         rf   r   zPage._onConsoleAPI  s    ()$99#>>!#99VR(( 	K 	KCMM$,;;GSIIJJJJfv66666rh   c                 j   t          j        |d                   }|d         }|d         }|d         } | j        |         | }d}t          j        ||||          }	 | j                            d||d         d           d S # t          $ r%}	t          j        t          |	           Y d }	~	d S d }	~	ww xY w)	Npayloadr  seqr   z
            function deliverResult(name, seq, result) {
                window[name]['callbacks'].get(seq)(result);
                window[name]['callbacks'].delete(seq);
            }
        zRuntime.evaluaterQ  )r
  	contextId)
jsonloadsr   r   r6  r   ra   rr   r   rs   )
r|   rk   objr  rW  r   rK  deliverResultr
  rz   s
             rf   r   zPage._onBindingCalled  s    jy)**6{%j6{)#D)40 ,]D#vNN
	)L0Z_`tZu2w2wxxxxx 	) 	) 	)fa(((((((((	)s   $B 
B2B--B2rn   c                 N   |                      t          j        j                  s8|D ]3}| j        j                            |                                           4d S g }|D ]z}|j        }|	                    d          r(|
                    |                                           F|
                    t          t          j        |                               {t          |d                    |          |          }|                     t          j        j        |           d S )NobjectId )	listenersr%   ry   r(   r   r   r   dispose_remoteObjectr   r  toStringr7  r   valueFromRemoteObjectr   joinrx   )r|   rn   r   r   
textTokensremoteObjectrO  s          rf   ru   zPage._addConsoleMessage  s   ~~dk122 	 > >"..s{{}}====F
 	S 	SC,L
++ S!!#,,..1111!!#f&B<&P&P"Q"QRRRR sxx
';';TBB		$+%w/////rh   c                    d}|                     d          }|dk    rt          j        j        }nG|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   rn   alertconfirmpromptbeforeunloadrO  defaultPrompt)r   r   TypeAlertConfirmPromptBeforeUnloadr   rx   r%   ry   )r|   rk   
dialogType_typer*   s        rf   r   zPage._onDialog  s    
		&!!G*JJi,JJh+JJn$$1Jj%))I2F2F		RaHbHbcc		$+$f-----rh   c                 @    | j         }|st          d          |j        S )zGet URL of this page.r   )r   r   rq   r|   r   s     rf   rq   zPage.url  s*      	.,---yrh   c                 j   K   | j         }|t          d          |                                 d{V S )z]Get the full HTML contents of the page.

        Returns HTML including the doctype.
        NNo main frame.)r   r   contentrv  s     rf   ry  zPage.content  sC      
 =,---]]__$$$$$$$rh   htmlc                 p   K   | j         }|t          d          |                    |           d{V  dS )z]Set content to this page.

        :arg str html: HTML markup to assign to the page.
        Nrx  )r   r   
setContent)r|   rz  r   s      rf   r|  zPage.setContent  sO      
 =,---t$$$$$$$$$$$rh   rq   c                    K   t          ||          }| j        j        }|t          d          | j                                                            dd          }i dt          ddffd}t          j	        | j        t          j        j        |          g}|                    d| j                  }t          | j        |||          }	|                     ||           d{V }
|
t          |
          |	                                 d{V }
|	                                 t          j        |           |
d	                                                                         }|r|                    |j                  }|r|j        n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.
        Nrx  refererr   reqrZ   c                 2    | j         vr| | j         <   d S d S r   )rq   )r  requestss    rf   set_requestzPage.goto.<locals>.set_request5  s*    wh&&$'!!! '&rh   r   r   )r    r   r   r   r   extraHTTPHeadersr   r   r   addEventListenerr   ry   r   r   	_navigatenavigationPromisecancelremoveEventListenerspopr   _navigationURLr1   )r|   rq   r!  r   r   referrerr  eventListenersr   watcherrK  r.   r0   r  s                @rf   gotoz	Page.goto  s     N Wf--&0	,---'88::>>y"MM')	(W 	( 	( 	( 	( 	( 	( 	( !1$2FH]Hegrttu++i)GHH"4#5y'7SS~~c844444444F###0022222222#N333q	))++ 	K,,y788#*4w4rh   r  c                    K   | j                             d||d           d {V }|                    d          r|d          d| S d S )NzPage.navigate)rq   r  	errorTextz at )r   ra   r   )r|   rq   r  r1   s       rf   r  zPage._navigateK  sj      **?CU]<^<^________<<$$ 	7{+66666trh   c                    K   t          ||          }t          j        |                     |          | j                            d                     d{V d         }|S )zVReload this page.

        Available options are same as :meth:`goto` method.
        zPage.reloadNr   )r    rb   rc   waitForNavigationr   ra   )r|   r!  r   r1   s       rf   reloadzPage.reloadQ  sd      
 Wf--!.)?)?)H)H$,J[J[\iJjJjllllllllnoprh   c                   
K   t          ||          }| j        j        }|t          d          |                    d| j                  }t          | j        |||          }i 
t          j        | j	        t          j        j        
fd          }|                                 d{V }t          j        |g           |d                                                                         }|r|
                    | j        d          }	|	S )a0  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 = asyncio.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.
        Nrx  r   c                 :                         | j        |           S r   )__setitem__rq   )r1   	responsess    rf   r   z(Page.waitForNavigation.<locals>.<lambda>  s    Y228<JJ rh   r   )r    r   r   r   r   r   r   r   r  r   r   ry   r   r  r  r  r   rq   )r|   r!  r   r   r   r  listenerrK  r.   r1   r  s             @rf   r  zPage.waitForNavigationZ  s     B Wf--&0	,---++i)GHH"4#5y'7SS)+	* !*JJJJ
 

 0022222222#XJ///q	))++ 	K==400rh   urlOrPredicatec                    K   t          ||          }|                    dd          }dt          dt          ffd}t	          j        | j        t          j        j        ||| j	        j
                   d{V 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   rj   r0   rZ   c                     t          t                    r| j        k    S t                    rt	           |                     S dS NF
isinstancer7  rq   callablebool)r0   r  s    rf   	predicatez&Page.waitForRequest.<locals>.predicate  sO    .#.. 5%44'' 5NN7334445rh   N)r    r   r   r  r   waitForEventr   r   ry   r   r   r|   r  r!  r   r   r  s    `    rf   waitForRequestzPage.waitForRequest  s      ( Wf--++i//	w 	4 	 	 	 	 	 	 ( ."7"?GUYUaUg
 
 
 
 
 
 
 
 	
rh   c                    K   t          ||          }|                    dd          }dt          dt          ffd}t	          j        | j        t          j        j        ||| j	        j
                   d{V S )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   rj   r1   rZ   c                     t          t                    r| j        k    S t                    rt	           |                     S dS r  r  )r1   r  s    rf   r  z'Page.waitForResponse.<locals>.predicate  sO    .#.. 6%55'' 6NN8445555rh   N)r    r   r   r  r   r  r   r   ry   r   r   r  s    `    rf   waitForResponsezPage.waitForResponse  s      ( Wf--++i//	 	T 	 	 	 	 	 	 ( ."7"@)WVZVbVh
 
 
 
 
 
 
 
 	
rh   c                 ^   K   t          ||          }|                     d|           d{V 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r|   r!  r   s      rf   goBackzPage.goBack  =       Wf--XXb'*********rh   c                 ^   K   t          ||          }|                     d|           d{V S )zNavigate to the next page in history.

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

        If cannot go forward, return ``None``.
           Nr  r  s      rf   	goForwardzPage.goForward  r  rh   deltac           
        K   | j                             d           d {V }|                    dd          |z   }|                    dg           }t          |          |k    rd S ||         }t	          j        |                     |          | j                             dd|                    d          i                     d {V d         }|S )NzPage.getNavigationHistorycurrentIndexr   entrieszPage.navigateToHistoryEntryentryIdid)r   ra   r   lenrb   rc   r  )r|   r  r!  history_countr  r   r1   s           rf   r  zPage._go  s      ))*EFFFFFFFF^Q//%7++i,,w<<6!!4.&&w//!!"?)UYYW[__A]^^         rh   c                 J   K   | j                             d           d{V  dS )z#Bring page to front (activate tab).zPage.bringToFrontNr   ra   r   s    rf   bringToFrontzPage.bringToFront  s5      l 344444444444rh   c                    K   t          ||          }|                     |                    di                      d{V  |                     |                    dd                     d{V  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.
        viewportNrB  r   )r    rd   r   rD  r  s      rf   emulatezPage.emulate  s      2 Wf-- w{{:r::;;;;;;;;;K < <===========rh   c                 z   K   | j         |k    rdS || _         | j                            dd| i           d{V  dS )zSet JavaScript enable/disable.Nz$Emulation.setScriptExecutionDisabledr   )r   r   ra   r   s     rf   setJavaScriptEnabledzPage.setJavaScriptEnabled  s[      "g--F")l FV]R]H_```````````rh   c                 P   K   | j                             dd|i           d{V  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.
        zPage.setBypassCSPr_   Nr  r   s     rf   setBypassCSPzPage.setBypassCSP!  s>       l 3i5IJJJJJJJJJJJrh   	mediaTypec                    K   |dvrt          d|           | j                            dd|pdi           d{V  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.setEmulatedMediamediar   N)
ValueErrorr   ra   )r|   r  s     rf   emulateMediazPage.emulateMedia+  sf       999C	CCDDDl <w	UW>YZZZZZZZZZZZrh   r  c                    K   | j                             |           d{V }|| _        |r|                                  d{V  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   emulateViewportr   r  )r|   r  needsReloads      rf   rd   zPage.setViewport7  so       !2BB8LLLLLLLL! 	 ++--	  	 rh   c                     | j         S )zuGet viewport as a dictionary or None.

        Fields of returned dictionary is same as :meth:`setViewport`.
        )r   r   s    rf   r  zPage.viewportG  s     ~rh   Fr.  r/  c                d   K   | j         }|t          d           |j        |g|R d|i d{V 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.
        Nrx  r/  )r   r   r0  )r|   r   r/  r   r   s        rf   r0  zPage.evaluateO  sW       =,---#U^LO4OOOJOOOOOOOOOrh   c                 t   K   t          j        |g|R  }| j                            dd|i           d{V  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   r6  r   ra   )r|   r   r   r   s       rf   evaluateOnNewDocumentzPage.evaluateOnNewDocument_  sW       (====l G(TZI\]]]]]]]]]]]rh   Tc                 R   K   | j                             dd| i           d{V  dS )zXEnable/Disable cache for each request.

        By default, caching is enabled.
        zNetwork.setCacheDisabledcacheDisabledNr  r   s     rf   setCacheEnabledzPage.setCacheEnabledk  sA      
 l :_RYk<Z[[[[[[[[[[[rh   c                 :  K   t          ||          }d}d|v r|d         }|dvrt          d|           nEd|v rAt          j        |d                   \  }}|dk    rd}n|dk    rd	}nt          d
|           |sd}|                     ||           d{V 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'``.
        Nrn   )pngjpegzUnknown type value: pathz	image/pngr  z
image/jpegr  z"Unsupported screenshot mime type: )r    r  	mimetypes
guess_type_screenshotTask)r|   r!  r   screenshotTypemimeType_s         rf   
screenshotzPage.screenshotr  s      4 Wf--W$V_N_44 !H!H!HIII 5w#.wv??KHa;&&!&\))!' !S!S!STTT 	#"N)).'BBBBBBBBBrh   formatc           	        K   | j                             dd| j        j        i           d {V  |                    d          |                    d          }}|rd|d<   |                    dd          }|                    d          r| j                             d           d {V }t          j        |d	         d
                   }t          j        |d	         d                   }t          dd||d          }| j        R| j                            dd          }	| j                            d|          }
| j                            dd          }nd}	|}
d}|rt          dd          }nt          dd          }| j                             d|	|||
|d           d {V  |                    d          r(| j                             dddddddi           d {V  d|i}|r||d<   |dk    r|||d<   | j                             d|           d {V }|                    d          r | j                             d           d {V  |                    d          r'| j         | 	                    | j                   d {V  |                    d          d k    r|                    d!d"          }n(t          j        |                    d!d"                    }|                    d#          }|r=t          |d$          5 }|                    |           d d d            n# 1 swxY w Y   |S )%NzTarget.activateTargettargetIdclipqualityr  scalefullPagezPage.getLayoutMetricscontentSizerF   rG   r   )xyrF   rG   r  isMobileFdeviceScaleFactorisLandscapeZ   landscapePrimary)anglern   portraitPrimaryz"Emulation.setDeviceMetricsOverride)mobilerF   rG   r  screenOrientationomitBackgroundz+Emulation.setDefaultBackgroundColorOverridecolor)rgbar  r  zPage.captureScreenshotencodingbase64datarh   r  wb)r   ra   r   	_targetIdr   mathceilr  r   rd   r  	b64decodeopenwrite)r|   r  r!  r  r  r  r?   rF   rG   r  r  	landscaper  optrK  buffer_pathfs                     rf   r  zPage._screenshotTask  s     l 7*dlF\9^_________F++W[[-C-Cg 	DMGQ'';;z"" 	 L--.EFFFFFFFFGIgm4W=>>EYw}5h?@@F !qfAFFFD~)++J>>$(N$6$67JE$R$R! N..}eDD		$)!!	 J$(r8J$K$K$K!!$(q7H$I$I$I!,##4$"$):): 	 	 	 	 	 	 	 	 	 ;;'(( 	,##=qWX_`ghIiIi?j           	CKV 3$C	N|(()A3GGGGGGGG;;'(( 	S,##$QRRRRRRRRR;;z"" 	3t~'A""4>222222222;;z""h..ZZ,,FF%fjj&=&=>>FF## 	 eT""  a                             s   L44L8;L8c                   K   t          ||          }|                    dd          }t          |                    d                    }|                    dd          }|                    dd          }t          |                    d                    }t          |                    d                    }|                    d	d          }	d
}
d}d|v rbt          j                            |d                                                   }|st          d|d         z             |d         }
|d         }nHt          |                    d                    p|
}
t          |                    d                    p|}|                    di           }t          |                    d                    pd}t          |                    d                    pd}t          |                    d                    pd}t          |                    d                    pd}|                    dd          }| j        	                    dt          |||||||
||||||	|                     d{V }t          j        |                    dd                    }d|v rCt          |d         d          5 }|                    |           ddd           n# 1 swxY w 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.
        r  r  displayHeaderFooterheaderTemplater   footerTemplateprintBackgroundr  
pageRangesrD   g      &@r  zUnknown paper format: rF   rG   margintopr   leftbottomrightpreferCSSPageSizeFzPage.printToPDF)r  r
  r  r  r  r  
paperWidthpaperHeight	marginTopmarginBottom
marginLeftmarginRightr  r  Nr  rh   r  r  )r    r   r  r%   rT   lowerr  convertPrintParameterToInchesr   ra   r  r  r  r  r  )r|   r!  r   r  r
  r  r  r  r  r  r  r  fmtmarginOptionsr  r  r  r  r  rK  r  r  s                         rf   pdfzPage.pdf  s(     B Wf--GQ''"7;;/D#E#EFF %5r:: %5r::w{{+<==>>[1122	[[r22

w#''(9(?(?(A(ABBC O !9GH<M!MNNNWJh-KK6w{{77K7KLLZPZJ7H8M8MNN]R]KHb111-2C2CE2J2JKKPq	2=3D3DV3L3LMMRQR
4]5F5Fx5P5PQQVUV3M4E4Eg4N4NOOTST#KK(;UCC|((#$7-- /%'#)%'%"3  
 
 
 
 
 
 
 
& !&**VS"9"9::Wgfot,,                               s   =KK#&K#c                 p   K   t                               d           |                     d           d{V S )z,[Deprecated] Get page content as plain text.z`Page.plainText` is deprecated.z() => document.body.innerTextN)rs   warningr0  r   s    rf   	plainTextzPage.plainTexty  s>      8999]]#BCCCCCCCCCrh   c                 j   K   | j         }|st          d          |                                 d{V S )zGet page's title.r   N)r   r   rH  rv  s     rf   rH  z
Page.title~  sD       	.,---[[]]"""""""rh   c                 d  K   t          ||          }| j        j        }|t          d          t	          |                    d                    }|r"| j                            d           d{V  dS |                    dd| j        j        i           d{V  | j        j	         d{V  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.runBeforeUnloadz
Page.closezTarget.closeTargetr  )
r    r   _connectionr   r  r   ra   r   r  r   )r|   r!  r   connr%  s        rf   r'   z
Page.close  s        Wf--|'<ijjjw{{+<==>> 	0,##L11111111111))0:t|?U2VWWWWWWWWW,//////////rh   c                     | j         S )z'Indicate that the page has been closed.)r   r   s    rf   isClosedzPage.isClosed  s
    |rh   c                     | j         S )z+Get :class:`~pyppeteer.input.Mouse` object.)r   r   s    rf   mousez
Page.mouse  s     {rh   c                 d   K   | j         }|t          d           |j        ||fi | d{V  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),
                )
        Nrx  )r   r   clickr|   r   r!  r   r   s        rf   r-  z
Page.click  sW      4 =,---ek(G66v66666666666rh   c                 p   K   | j         }|t          d          |                    |           d{V  dS )zMouse hover the element which matches ``selector``.

        If no element matched the ``selector``, raise ``PageError``.
        Nrx  )r   r   hoverr   s      rf   r0  z
Page.hover  M      
 =,---kk(###########rh   c                 p   K   | j         }|t          d          |                    |           d{V  dS )z|Focus the element which matches ``selector``.

        If no element matched the ``selector``, raise ``PageError``.
        Nrx  )r   r   focusr   s      rf   r3  z
Page.focus  r1  rh   r   c                 ^   K   | j         }|st          d           |j        |g|R   d{V S )zSelect options and return selected values.

        If no element matched the ``selector``, raise ``ElementHandleError``.
        r   N)r   r   select)r|   r   r   r   s       rf   r5  zPage.select  sR      
  	.,---!U\(4V4444444444rh   r   c                 b   K   | j         }|st          d           |j        |||fi | d{V 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   rn   )r|   r   r   r!  r   r   s         rf   rn   z	Page.type  sV        	.,---UZ$BB6BBBBBBBBBrh   selectorOrFunctionOrTimeoutc                 V    | 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)r|   r7  r!  r   r   r   s         rf   r9  zPage.waitFor  sG    <  	.,---u}8'SDSSSFSSSrh   c                 P    | 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.  s        rf   r;  zPage.waitForSelector  s?    .  	.,---$u$XwAA&AAArh   r  c                 P    | j         }|st          d           |j        ||fi |S )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)r|   r  r!  r   r   s        rf   r=  zPage.waitForXPath1  s?    0  	.,---!u!%;;F;;;rh   c                 V    | j         }|st          d           |j        ||g|R i |S )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)r|   r   r!  r   r   r   s         rf   r?  zPage.waitForFunctionN  sG    2  	.,---$u$\7LTLLLVLLLrh   r  r   )rZ   r#   )rZ   r"   )rZ   r   )rZ   N)T){__name__
__module____qualname____doc__r   ry   r  rT   r   r7  float__annotations__staticmethodr   r  r
   r   rg   r   propertyrV   r   r   r   r   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  JJevalJJJJevalJxr   r  r  r   r#  r&  r)  r   r;  r>  rA  rD  r?   r   rF  rv   r   r   ru   r   rq   ry  r|  r   r  r  r  r  r   r  r  r  r  r  r  r  r  r  r  rd   r  r0  r  r  bytesr  r  r  r"  rH  r'   r)  r   r+  r-  r0  r3  r5  rn   r   r9  r;  r=  r?  __classcell__)r   s   @rf   r%   r%   (   s          _   g	 x ,+	
 g + 	  &o *) &o &o (' V 	  &o!" *)#F( 15++r**++r**T**T**T**T**T**T**1 1 1L$sDe,,-     %)    "$	
 " 
   \B %)S@ S@S@ S@ 	S@
  S@ "S@ 
S@ S@ S@ S@ S@ S@j    X $ $ $ X$7c 7S 7T 7 7 7 7
Hd 
Ht 
H 
H 
H 
H -8G, - - - X- (    X ![ ! ! ! X! (    X"# "$ " " " "    X 1W 1 1 1 X1 ,f , , , X,!H$ !H4 !H !H !H !HF;D ;T ; ; ; ;13 14 1 1 1 1""# "D "T " " " "
 
 
 
 
 
3C 3H]4K 3 3 3 3A AS AX A A A A 
;( 
;x 
; 
; 
; 
;L L3 Ls LWZ L L L L O3 Oc ORU OZ] O O O O6s 6tM7J 6 6 6 6
-c 
-d=.A 
- 
- 
- 
- 	AE	B!F	B'3 '4S%S$:O5O0P+Q ' ' ' '2C4 CD C C C C$O O O O O OB1 1$ 1 1 1 1 1 1&0 0 0 0 0 0 0 0"0 0 0 0 0 0+f +f#s(AS +fX\ +f +f +f +fZDd38n D D D D DGc3h GD G G G G BC BD B B B B=tCH~ = = = =6
$ 
4 
 
 
 

4 DcN    = =$ = = = =74 7D 7 7 7 7)d )t ) ) ) )(0s 0$x. 0T 0 0 0 0".s .t . . . . S    X%s % % % %%S %T % % % %C5 C5c C5D C53 C58T\K] C5 C5 C5 C5J3 # (3-     D 3 8HCU    4 4t 4c 4hW_N` 4 4 4 4n VZ 
  
#C7)T/)B$BC 
NR 
eh 
	 
  
  
  
F W[ 
  
#C8*d2B)C$CD 
OS 
fi 
	 
  
  
  
D+ +D +3 +8HCU + + + ++ +t +c +hxFX + + + +s T hx6H    5 5 5 5> >T >C >D > > > >>a$ a4 a a a aK$ K4 K K K K
[ 
[C 
[4 
[ 
[ 
[ 
[ $  4          (4.    X PU P P P3 Ps P PY\ P P P P 
^ 
^C 
^D 
^ 
^ 
^ 
^\ \T \T \ \ \ \*C *C *Cs *CuUTWZGX *C *C *C *CXCC C$ C5PSCT C C C CJT T T T T T T TlD D D D D
#S # # # #0 04 0# 0$ 0 0 0 06$     u    X7 7C 7$ 7 7QU 7 7 7 7>$C $D $ $ $ $$C $D $ $ $ $5S 53 549 5 5 5 5
C 
C3 
Cc 
CD 
CSV 
C[_ 
C 
C 
C 
C TX!T !T+0c5+A!TLP!T`c!Tor!T	!T !T !T !TFB B Bd BS BU^ B B B B8< <# < <s <y < < < <:M MC M$ Mc M]` Men M M M M M M M Mrh   r%   )	Timestamp	DocumentsFramesJSEventListenersNodesLayoutCountRecalcStyleCountLayoutDurationRecalcStyleDurationScriptDurationTaskDurationJSHeapUsedSizeJSHeapTotalSizer  `   gfffffB@g=
ףp=@)pxincmmm	parameterrZ   c                    | dS t          | t          t          f          r| }nt          | t                    rx| }|dd                                         }|t
          v r|dd         }nd}|}	 t          |          }n # t          $ r t          d|z             w xY w|t
          |         z  }n,t          dt          t          |                     z             |dz  S )z"Convert print parameter to inches.Nr^  z!Failed to parse parameter value: z)page.pdf() Cannot handle parameter type: r]  )	r  rH  rD  r7  r  unitToPixelsr  	TypeErrorrn   )rb  pixelsr   unit	valueTextr   s         rf   r  r    s   t)c5\** \	Is	#	# \BCCy  <SbS	IIDI	I)$$EE 	I 	I 	I@4GHHH	Id++Cc$y//FZFZZ[[[B;s   0B   Bc            	           e Zd ZdZddededee         ddfdZedefd            Z	edefd	            Z
edee         fd
            ZdS )r   ziConsole message class.

    ConsoleMessage objects are dispatched by page via the ``console`` event.
    Nrn   r   r   rZ   c                 8    || _         || _        ||ng | _        d S r   )rt  _text_args)r|   rn   r   r   s       rf   r   zConsoleMessage.__init__  s$    

!-TT2


rh   c                     | j         S )zReturn type of this message.)rt  r   s    rf   rn   zConsoleMessage.type       zrh   c                     | j         S )z+Return text representation of this message.)rl  r   s    rf   r   zConsoleMessage.text  ro  rh   c                     | j         S )z/Return list of args (JSHandle) of this message.)rm  r   s    rf   r   zConsoleMessage.args  ro  rh   r   )r@  rA  rB  rC  r7  r	   r   r   rG  rn   r   r   r  rh   rf   r   r     s         
6 6S 6 64> 6T 6 6 6 6 c    X c    X d8n    X  rh   r   )HrC  rb   r  rY  loggingr  r  typesr   typingr   r   r   r   r   r	   r
   r   pyeer   	pyppeteerr   pyppeteer.connectionr   pyppeteer.coverager   pyppeteer.dialogr   pyppeteer.element_handler   pyppeteer.emulation_managerr   pyppeteer.errorsr   pyppeteer.execution_contextr   pyppeteer.frame_managerr   r   pyppeteer.helperr   pyppeteer.inputr   r   r   pyppeteer.navigator_watcherr   pyppeteer.network_managerr   r   r   pyppeteer.tracingr   pyppeteer.utilr    pyppeteer.workerr!   pyppeteer.browserr"   r#   	getLoggerr@  rs   r%   rJ  re  rH  rD  r7  r  objectr   r  rh   rf   <module>r     s              ! ! ! ! ! ! W W W W W W W W W W W W W W W W W W W W             + + + + + + ' ' ' ' ' ' # # # # # # 2 2 2 2 2 2 8 8 8 8 8 8 & & & & & & 0 0 0 0 0 0 ) ) ) ) ) ) 0 0 0 0 0 0 ' ' ' ' ' ' 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 G G G G G G G G G G % % % % % % % % % % % % # # # # # # 211111111		8	$	$BM BM BM BM BM< BM BM BMJ2 " rT::U4eS3H-I hW\o    0    V     rh   