How to use the pyppeteer.helper function in pyppeteer

To help you get started, we’ve selected a few pyppeteer examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github miyakogi / pyppeteer / pyppeteer / page.py View on Github external
def _onLogEntryAdded(self, event: Dict) -> None:
        entry = event.get('entry', {})
        level = entry.get('level', '')
        text = entry.get('text', '')
        args = entry.get('args', [])
        source = entry.get('source', '')
        for arg in args:
            helper.releaseObject(self._client, arg)

        if source != 'worker':
            self.emit(Page.Events.Console, ConsoleMessage(level, text))
github miyakogi / pyppeteer / pyppeteer / frame_manager.py View on Github external
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.'
github miyakogi / pyppeteer / pyppeteer / page.py View on Github external
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
        """  # noqa: E501
        options = merge_dict(options, kwargs)
        timeout = options.get('timeout', 30000)

        def predicate(response: Response) -> bool:
            if isinstance(urlOrPredicate, str):
                return urlOrPredicate == response.url
            if callable(urlOrPredicate):
                return bool(urlOrPredicate(response))
            return False

        return await helper.waitForEvent(
            self._networkManager,
            NetworkManager.Events.Response,
            predicate,
            timeout,
            self._client._loop,
        )
github miyakogi / pyppeteer / pyppeteer / page.py View on Github external
def _onBindingCalled(self, event: Dict) -> None:
        obj = json.loads(event['payload'])
        name = obj['name']
        seq = obj['seq']
        args = obj['args']
        result = self._pageBindings[name](*args)

        deliverResult = '''
            function deliverResult(name, seq, result) {
                window[name]['callbacks'].get(seq)(result);
                window[name]['callbacks'].delete(seq);
            }
        '''

        expression = helper.evaluationString(deliverResult, name, seq, result)
        try:
            self._client.send('Runtime.evaluate', {
                'expression': expression,
                'contextId': event['executionContextId'],
            })
        except Exception as e:
            helper.debugError(logger, e)
github miyakogi / pyppeteer / pyppeteer / execution_context.py View on Github external
async def dispose(self) -> None:
        """Stop referencing the handle."""
        if self._disposed:
            return
        self._disposed = True
        try:
            await helper.releaseObject(self._client, self._remoteObject)
        except Exception as e:
            debugError(logger, e)
github miyakogi / pyppeteer / pyppeteer / emulation_manager.py View on Github external
async def emulateViewport(self, viewport: dict) -> bool:
        """Evaluate viewport."""
        options = dict()
        mobile = viewport.get('isMobile', False)
        options['mobile'] = mobile
        if 'width' in viewport:
            options['width'] = helper.get_positive_int(viewport, 'width')
        if 'height' in viewport:
            options['height'] = helper.get_positive_int(viewport, 'height')

        options['deviceScaleFactor'] = viewport.get('deviceScaleFactor', 1)
        if viewport.get('isLandscape'):
            options['screenOrientation'] = {'angle': 90,
                                            'type': 'landscapePrimary'}
        else:
            options['screenOrientation'] = {'angle': 0,
                                            'type': 'portraitPrimary'}
        hasTouch = viewport.get('hasTouch', False)

        await self._client.send('Emulation.setDeviceMetricsOverride', options)
        await self._client.send('Emulation.setTouchEmulationEnabled', {
            'enabled': hasTouch,
            'configuration': 'mobile' if mobile else 'desktop'
github miyakogi / pyppeteer / pyppeteer / execution_context.py View on Github external
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 self._objectHandleFactory(remoteObject)
github miyakogi / pyppeteer / pyppeteer / execution_context.py View on Github external
def toString(self) -> str:
        """Get string representation."""
        if self._remoteObject.get('objectId'):
            _type = (self._remoteObject.get('subtype') or
                     self._remoteObject.get('type'))
            return f'JSHandle@{_type}'
        return 'JSHandle:{}'.format(
            helper.valueFromRemoteObject(self._remoteObject))