Esempio n. 1
0
    def waitFor(self, selectorOrFunctionOrTimeout: Union[str, int, float],
                options: dict = None, *args: Any, **kwargs: Any
                ) -> Union[Awaitable, 'WaitTask']:
        """Wait until `selectorOrFunctionOrTimeout`.

        Details see :meth:`pyppeteer.page.Page.waitFor`.
        """
        options = merge_dict(options, kwargs)
        if isinstance(selectorOrFunctionOrTimeout, (int, float)):
            fut: Awaitable[None] = self._client._loop.create_task(
                asyncio.sleep(selectorOrFunctionOrTimeout / 1000))
            return fut
        if not isinstance(selectorOrFunctionOrTimeout, str):
            fut = self._client._loop.create_future()
            fut.set_exception(TypeError(
                'Unsupported target type: ' +
                str(type(selectorOrFunctionOrTimeout))
            ))
            return fut

        if args or helper.is_jsfunc(selectorOrFunctionOrTimeout):
            return self.waitForFunction(
                selectorOrFunctionOrTimeout, options, *args)
        if selectorOrFunctionOrTimeout.startswith('//'):
            return self.waitForXPath(selectorOrFunctionOrTimeout, options)
        return self.waitForSelector(selectorOrFunctionOrTimeout, options)
Esempio n. 2
0
    def waitFor(self, selectorOrFunctionOrTimeout: Union[str, int, float],
                options: dict = None, *args: Any, **kwargs: Any
                ) -> Union[Awaitable, 'WaitTask']:
        """Wait until `selectorOrFunctionOrTimeout`.

        Details see :meth:`pyppeteer.page.Page.waitFor`.
        """
        options = merge_dict(options, kwargs)
        if isinstance(selectorOrFunctionOrTimeout, (int, float)):
            fut: Awaitable[None] = asyncio.ensure_future(
                asyncio.sleep(selectorOrFunctionOrTimeout / 1000))
            return fut
        if not isinstance(selectorOrFunctionOrTimeout, str):
            fut = asyncio.get_event_loop().create_future()
            fut.set_exception(TypeError(
                'Unsupported target type: ' +
                str(type(selectorOrFunctionOrTimeout))
            ))
            return fut

        if args or helper.is_jsfunc(selectorOrFunctionOrTimeout):
            return self.waitForFunction(
                selectorOrFunctionOrTimeout, options, *args)
        if selectorOrFunctionOrTimeout.startswith('//'):
            return self.waitForXPath(selectorOrFunctionOrTimeout, options)
        return self.waitForSelector(selectorOrFunctionOrTimeout, options)
Esempio n. 3
0
    async def evaluateHandle(self, pageFunction: str, *args: Any,
                             force_expr: bool = False) -> 'JSHandle':
        """Execute ``pageFunction`` on this context.

        Details see :meth:`pyppeteer.page.Page.evaluateHandle`.
        """
        if force_expr or (not args and not helper.is_jsfunc(pageFunction)):
            _obj = await self._client.send('Runtime.evaluate', {
                'expression': pageFunction,
                'contextId': self._contextId,
                'returnByValue': False,
                'awaitPromise': True,
            })
            exceptionDetails = _obj.get('exceptionDetails')
            if exceptionDetails:
                raise ElementHandleError(
                    'Evaluation failed: {}'.format(
                        helper.getExceptionMessage(exceptionDetails)))
            remoteObject = _obj.get('result')
            return self._objectHandleFactory(remoteObject)

        _obj = await self._client.send('Runtime.callFunctionOn', {
            'functionDeclaration': pageFunction,
            'executionContextId': self._contextId,
            'arguments': [self._convertArgument(arg) for arg in args],
            'returnByValue': False,
            'awaitPromise': True,
        })
        exceptionDetails = _obj.get('exceptionDetails')
        if exceptionDetails:
            raise ElementHandleError('Evaluation failed: {}'.format(
                helper.getExceptionMessage(exceptionDetails)))
        remoteObject = _obj.get('result')
        return self._objectHandleFactory(remoteObject)
Esempio n. 4
0
    async def evaluateHandle(self, pageFunction: str,
                             *args: Any) -> 'JSHandle':
        """Execute `pageFunction` on this context."""
        if not args and not helper.is_jsfunc(pageFunction):
            _obj = await self._client.send(
                'Runtime.evaluate', {
                    'expression': pageFunction,
                    'contextId': self._contextId,
                    'returnByValue': False,
                    'awaitPromiss': True,
                })
            exceptionDetails = _obj.get('exceptionDetails')
            if exceptionDetails:
                raise ElementHandleError('Evaluation failed: {}'.format(
                    helper.getExceptionMessage(exceptionDetails)))
            remoteObject = _obj.get('result')
            return self._objectHandleFactory(remoteObject)

        _obj = await self._client.send(
            'Runtime.callFunctionOn', {
                'functionDeclaration': pageFunction,
                'executionContextId': self._contextId,
                'arguments': [self._convertArgument(arg) for arg in args],
                'returnByValue': False,
                'awaitPromiss': True,
            })
        exceptionDetails = _obj.get('exceptionDetails')
        if exceptionDetails:
            raise ElementHandleError('Evaluation failed: {}'.format(
                helper.getExceptionMessage(exceptionDetails)))
        remoteObject = _obj.get('result')
        return self._objectHandleFactory(remoteObject)
Esempio n. 5
0
 async def evaluateHandle(self,
                          pageFunction: str,
                          *args: Any,
                          force_expr: bool = False) -> 'JSHandle':
     'Execute ``pageFunction`` on this context.\n\n        Details see :meth:`pyppeteer.page.Page.evaluateHandle`.\n        '
     if (force_expr
             or ((not args) and (not helper.is_jsfunc(pageFunction)))):
         _obj = (await self._client.send(
             'Runtime.evaluate', {
                 'expression': pageFunction,
                 'contextId': self._contextId,
                 'returnByValue': False,
                 'awaitPromise': True,
             }))
         exceptionDetails = _obj.get('exceptionDetails')
         if exceptionDetails:
             raise ElementHandleError('Evaluation failed: {}'.format(
                 helper.getExceptionMessage(exceptionDetails)))
         remoteObject = _obj.get('result')
         return self._objectHandleFactory(remoteObject)
     _obj = (await self._client.send(
         'Runtime.callFunctionOn', {
             'functionDeclaration': pageFunction,
             'executionContextId': self._contextId,
             'arguments': [self._convertArgument(arg) for arg in args],
             'returnByValue': False,
             'awaitPromise': True,
         }))
     exceptionDetails = _obj.get('exceptionDetails')
     if exceptionDetails:
         raise ElementHandleError('Evaluation failed: {}'.format(
             helper.getExceptionMessage(exceptionDetails)))
     remoteObject = _obj.get('result')
     return self._objectHandleFactory(remoteObject)
 async def evaluateHandle(self,
                          pageFunction: str,
                          *args: Any,
                          force_expr: bool = False) -> 'JSHandle':
     'Execute ``pageFunction`` on this context.\n\n        Details see :meth:`pyppeteer.page.Page.evaluateHandle`.\n        '
     suffix = ''.join(
         ['//# sourceURL=', '{}'.format(EVALUATION_SCRIPT_URL)])
     if (force_expr
             or ((not args) and (not helper.is_jsfunc(pageFunction)))):
         try:
             if SOURCE_URL_REGEX.match(pageFunction):
                 expressionWithSourceUrl = pageFunction
             else:
                 expressionWithSourceUrl = ''.join(
                     ['{}'.format(pageFunction), '\n', '{}'.format(suffix)])
             _obj = (await self._client.send(
                 'Runtime.evaluate', {
                     'expression': expressionWithSourceUrl,
                     'contextId': self._contextId,
                     'returnByValue': False,
                     'awaitPromise': True,
                     'userGesture': True,
                 }))
         except Exception as e:
             _rewriteError(e)
         exceptionDetails = _obj.get('exceptionDetails')
         if exceptionDetails:
             raise ElementHandleError('Evaluation failed: {}'.format(
                 helper.getExceptionMessage(exceptionDetails)))
         remoteObject = _obj.get('result')
         return self._objectHandleFactory(remoteObject)
     try:
         _obj = (await self._client.send(
             'Runtime.callFunctionOn', {
                 'functionDeclaration':
                 ''.join([
                     '{}'.format(pageFunction), '\n', '{}'.format(suffix),
                     '\n'
                 ]),
                 'executionContextId':
                 self._contextId,
                 'arguments': [self._convertArgument(arg) for arg in args],
                 'returnByValue':
                 False,
                 'awaitPromise':
                 True,
                 'userGesture':
                 True,
             }))
     except Exception as e:
         _rewriteError(e)
     exceptionDetails = _obj.get('exceptionDetails')
     if exceptionDetails:
         raise ElementHandleError('Evaluation failed: {}'.format(
             helper.getExceptionMessage(exceptionDetails)))
     remoteObject = _obj.get('result')
     return self._objectHandleFactory(remoteObject)
Esempio n. 7
0
    async def evaluateHandle(
            self,
            pageFunction: str,
            *args: Any,  # noqa: C901
            force_expr: bool = False) -> 'JSHandle':
        """Execute ``pageFunction`` on this context.

        Details see :meth:`pyppeteer.page.Page.evaluateHandle`.
        """
        suffix = f'//# sourceURL={EVALUATION_SCRIPT_URL}'

        if force_expr or (not args and not helper.is_jsfunc(pageFunction)):
            try:
                if SOURCE_URL_REGEX.match(pageFunction):
                    expressionWithSourceUrl = pageFunction
                else:
                    expressionWithSourceUrl = f'{pageFunction}\n{suffix}'
                _obj = await self._client.send(
                    'Runtime.evaluate', {
                        'expression': expressionWithSourceUrl,
                        'contextId': self._contextId,
                        'returnByValue': False,
                        'awaitPromise': True,
                        'userGesture': True,
                    })
            except Exception as e:
                _rewriteError(e)

            exceptionDetails = _obj.get('exceptionDetails')
            if exceptionDetails:
                raise ElementHandleError('Evaluation failed: {}'.format(
                    helper.getExceptionMessage(exceptionDetails)))
            remoteObject = _obj.get('result')
            return createJSHandle(self, remoteObject)

        try:
            _obj = await self._client.send(
                'Runtime.callFunctionOn', {
                    'functionDeclaration': f'{pageFunction}\n{suffix}\n',
                    'executionContextId': self._contextId,
                    'arguments': [self._convertArgument(arg) for arg in args],
                    'returnByValue': False,
                    'awaitPromise': True,
                    'userGesture': True,
                })
        except Exception as e:
            _rewriteError(e)

        exceptionDetails = _obj.get('exceptionDetails')
        if exceptionDetails:
            raise ElementHandleError('Evaluation failed: {}'.format(
                helper.getExceptionMessage(exceptionDetails)))
        remoteObject = _obj.get('result')
        return createJSHandle(self, remoteObject)
    def __init__(
            self,
            frame: Frame,
            predicateBody: str,  # noqa: C901
            title: str,
            polling: Union[str, int],
            timeout: float,
            loop: asyncio.AbstractEventLoop,
            *args: Any) -> None:
        if isinstance(polling, str):
            if polling not in ['raf', 'mutation']:
                raise ValueError(f'Unknown polling: {polling}')
        elif isinstance(polling, (int, float)):
            if polling <= 0:
                raise ValueError(
                    f'Cannot poll with non-positive interval: {polling}')
        else:
            raise ValueError(f'Unknown polling option: {polling}')

        self._frame = frame
        self._polling = polling
        self._timeout = timeout
        self._loop = loop
        if args or helper.is_jsfunc(predicateBody):
            self._predicateBody = f'return ({predicateBody})(...args)'
        else:
            self._predicateBody = f'return {predicateBody}'
        self._args = args
        self._runCount = 0
        self._terminated = False
        self._timeoutError = False
        frame._waitTasks.add(self)

        self.promise = self._loop.create_future()

        async def timer(timeout: Union[int, float]) -> None:
            await asyncio.sleep(timeout / 1000)
            self._timeoutError = True
            self.terminate(
                TimeoutError(
                    f'Waiting for {title} failed: timeout {timeout}ms exceeds.'
                ))

        if timeout:
            self._timeoutTimer = self._loop.create_task(timer(self._timeout))
        self._runningTask = self._loop.create_task(self.rerun())
Esempio n. 9
0
    def __init__(self, frame: Frame, predicateBody: str, title: str,
                 polling: Union[(str, int)], timeout: float,
                 loop: asyncio.AbstractEventLoop, *args: Any) -> None:
        if isinstance(polling, str):
            if (polling not in ['raf', 'mutation']):
                raise ValueError(''.join(
                    ['Unknown polling: ', '{}'.format(polling)]))
        elif isinstance(polling, (int, float)):
            if (polling <= 0):
                raise ValueError(''.join([
                    'Cannot poll with non-positive interval: ',
                    '{}'.format(polling)
                ]))
        else:
            raise ValueError(''.join(
                ['Unknown polling option: ', '{}'.format(polling)]))
        self._frame = frame
        self._polling = polling
        self._timeout = timeout
        self._loop = loop
        if (args or helper.is_jsfunc(predicateBody)):
            self._predicateBody = ''.join(
                ['return (', '{}'.format(predicateBody), ')(...args)'])
        else:
            self._predicateBody = ''.join(
                ['return ', '{}'.format(predicateBody)])
        self._args = args
        self._runCount = 0
        self._terminated = False
        self._timeoutError = False
        frame._waitTasks.add(self)
        self.promise = self._loop.create_future()

        async def timer(timeout: Union[(int, float)]) -> None:
            (await asyncio.sleep((timeout / 1000)))
            self._timeoutError = True
            self.terminate(
                TimeoutError(''.join([
                    'Waiting for ', '{}'.format(title), ' failed: timeout ',
                    '{}'.format(timeout), 'ms exceeds.'
                ])))

        if timeout:
            self._timeoutTimer = self._loop.create_task(timer(self._timeout))
        self._runningTask = self._loop.create_task(self.rerun())
Esempio n. 10
0
    def __init__(self, frame: Frame, predicateBody: str,  # noqa: C901
                 title: str, polling: Union[str, int], timeout: float,
                 loop: asyncio.AbstractEventLoop, *args: Any) -> None:
        if isinstance(polling, str):
            if polling not in ['raf', 'mutation']:
                raise ValueError(f'Unknown polling: {polling}')
        elif isinstance(polling, (int, float)):
            if polling <= 0:
                raise ValueError(
                    f'Cannot poll with non-positive interval: {polling}'
                )
        else:
            raise ValueError(f'Unknown polling option: {polling}')

        self._frame = frame
        self._polling = polling
        self._timeout = timeout
        self._loop = loop
        if args or helper.is_jsfunc(predicateBody):
            self._predicateBody = f'return ({predicateBody})(...args)'
        else:
            self._predicateBody = f'return {predicateBody}'
        self._args = args
        self._runCount = 0
        self._terminated = False
        self._timeoutError = False
        frame._waitTasks.add(self)

        self.promise = self._loop.create_future()

        async def timer(timeout: Union[int, float]) -> None:
            await asyncio.sleep(timeout / 1000)
            self._timeoutError = True
            self.terminate(TimeoutError(
                f'Waiting for {title} failed: timeout {timeout}ms exceeds.'
            ))

        if timeout:
            self._timeoutTimer = self._loop.create_task(timer(self._timeout))
        self._runningTask = self._loop.create_task(self.rerun())
Esempio n. 11
0
 def waitFor(self,
             selectorOrFunctionOrTimeout: Union[(str, int, float)],
             options: dict = None,
             *args: Any,
             **kwargs: Any) -> Union[(Awaitable, 'WaitTask')]:
     'Wait until `selectorOrFunctionOrTimeout`.\n\n        Details see :meth:`pyppeteer.page.Page.waitFor`.\n        '
     options = merge_dict(options, kwargs)
     if isinstance(selectorOrFunctionOrTimeout, (int, float)):
         fut = self._client._loop.create_task(
             asyncio.sleep((selectorOrFunctionOrTimeout / 1000)))
         return fut
     if (not isinstance(selectorOrFunctionOrTimeout, str)):
         fut = self._client._loop.create_future()
         fut.set_exception(
             TypeError(('Unsupported target type: ' +
                        str(type(selectorOrFunctionOrTimeout)))))
         return fut
     if (args or helper.is_jsfunc(selectorOrFunctionOrTimeout)):
         return self.waitForFunction(selectorOrFunctionOrTimeout, options,
                                     *args)
     if selectorOrFunctionOrTimeout.startswith('//'):
         return self.waitForXPath(selectorOrFunctionOrTimeout, options)
     return self.waitForSelector(selectorOrFunctionOrTimeout, options)