Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
async def test_default_context(self):
self.assertEqual(len(self.browser.browserContexts), 1)
defaultContext = self.browser.browserContexts[0]
self.assertFalse(defaultContext.isIncognito())
with self.assertRaises(BrowserError) as cm:
await defaultContext.close()
self.assertIn('cannot be closed', cm.exception.args[0])
'form[action="/kmsi"]', timeout=self._AWAIT_TIMEOUT)
await page.waitForSelector('#idBtn_Back')
await page.click('#idBtn_Back')
page.on('request', _saml_response)
await page.setRequestInterception(True)
wait_time = time.time() + self._MFA_TIMEOUT
while time.time() < wait_time and not self.saml_response:
if await self._querySelector(page, '.has-error'):
raise FormError
if not self.saml_response:
raise TimeoutError
except (TimeoutError, BrowserError, FormError) as e:
print('An error occurred while authenticating, check credentials.')
print(e)
if self._debug:
debugfile = 'aadaerror-{}.png'.format(
datetime.now().strftime("%Y-%m-%dT%H%m%SZ"))
await page.screenshot({'path': debugfile})
print('See screenshot {} for clues.'.format(debugfile))
exit(1)
finally:
await browser.close()
async def _targetInfoChanged(self, event: Dict) -> None:
target = self._targets.get(event['targetInfo']['targetId'])
if not target:
raise BrowserError('target should exist before targetInfoChanged')
previousURL = target.url
wasInitialized = target._isInitialized
target._targetInfoChanged(event['targetInfo'])
if wasInitialized and previousURL != target.url:
self.emit(Browser.Events.TargetChanged, target)
target.browserContext.emit(BrowserContext.Events.TargetChanged, target) # noqa: E501
async def _createPageInContext(self, contextId: Optional[str]) -> Page:
options = {'url': 'about:blank'}
if contextId:
options['browserContextId'] = contextId
targetId = (await self._connection.send(
'Target.createTarget', options)).get('targetId')
target = self._targets.get(targetId)
if target is None:
raise BrowserError('Failed to create target for page.')
if not await target._initializedPromise:
raise BrowserError('Failed to create target for page.')
page = await target.page()
if page is None:
raise BrowserError('Failed to create page.')
return page
Defaults to ``False``.
* ``slowMo`` (int|float): Slow down pyppeteer's by the specified amount of
milliseconds.
* ``logLevel`` (int|str): Log level to print logs. Defaults to same as the
root logger.
* ``loop`` (asyncio.AbstractEventLoop): Event loop (**experimental**).
"""
options = merge_dict(options, kwargs)
logLevel = options.get('logLevel')
if logLevel:
logging.getLogger('pyppeteer').setLevel(logLevel)
browserWSEndpoint = options.get('browserWSEndpoint')
if not browserWSEndpoint:
raise BrowserError('Need `browserWSEndpoint` option.')
connectionDelay = options.get('slowMo', 0)
connection = Connection(browserWSEndpoint,
options.get('loop', asyncio.get_event_loop()),
connectionDelay)
browserContextIds = (await connection.send('Target.getBrowserContexts')
).get('browserContextIds', [])
ignoreHTTPSErrors = bool(options.get('ignoreHTTPSErrors', False))
defaultViewport = options.get('defaultViewport',
{'width': 800, 'height': 600})
return await Browser.create(
connection, browserContextIds, ignoreHTTPSErrors, defaultViewport,
None, lambda: connection.send('Browser.close'))
async def close(self) -> None:
"""Close the browser context.
All the targets that belongs to the browser context will be closed.
.. note::
Only incognito browser context can be closed.
"""
if self._id is None:
raise BrowserError('Non-incognito profile cannot be closed')
await self._browser._disposeContext(self._id)
def _get_ws_endpoint(self) -> str:
url = self.url + '/json/version'
while self.proc.poll() is None:
time.sleep(0.1)
try:
with urlopen(url) as f:
data = json.loads(f.read().decode())
break
except URLError:
continue
else:
raise BrowserError(
'Browser closed unexpectedly:\n{}'.format(
self.proc.stdout.read().decode()
)
)
return data['webSocketDebuggerUrl']
async def _createPageInContext(self, contextId: Optional[str]) -> Page:
options = {'url': 'about:blank'}
if contextId:
options['browserContextId'] = contextId
targetId = (await self._connection.send(
'Target.createTarget', options)).get('targetId')
target = self._targets.get(targetId)
if target is None:
raise BrowserError('Failed to create target for page.')
if not await target._initializedPromise:
raise BrowserError('Failed to create target for page.')
page = await target.page()
if page is None:
raise BrowserError('Failed to create page.')
return page
async def _get_ws_endpoint(self) -> str:
url = self.url + '/json/version'
while self.proc.returncode is None:
await asyncio.sleep(0.1)
try:
with urlopen(url) as f:
data = json.loads(f.read().decode())
break
except URLError:
continue
else:
raise BrowserError(
'Browser closed unexpectedly:\n{}'.format(
await self.proc.stdout.read().decode()
)
)
return data['webSocketDebuggerUrl']