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 launch(self):
self.chromeClosed = False
self.connection = None
env = self.options.get("env")
self.proc = await asyncio.subprocess.create_subprocess_exec(
*self.cmd,
stdout=asyncio.subprocess.DEVNULL,
stderr=asyncio.subprocess.DEVNULL,
env=env,
)
# Signal handlers for exits used to be here
connectionDelay = self.options.get("slowMo", 0)
self.browserWSEndpoint = await self._get_ws_endpoint()
self.connection = Connection(
self.browserWSEndpoint, self._loop, connectionDelay)
return await Browser.create(
self.connection, self.options, self.proc, self.killChrome)
# don't forget to close browser process
if self.autoClose:
atexit.register(_close_process)
if self.handleSIGINT:
signal.signal(signal.SIGINT, _close_process)
if self.handleSIGTERM:
signal.signal(signal.SIGTERM, _close_process)
if not sys.platform.startswith('win'):
# SIGHUP is not defined on windows
if self.handleSIGHUP:
signal.signal(signal.SIGHUP, _close_process)
connectionDelay = self.slowMo
self.browserWSEndpoint = self._get_ws_endpoint()
logger.info(f'Browser listening on: {self.browserWSEndpoint}')
self.connection = Connection(
self.browserWSEndpoint,
self._loop,
connectionDelay,
)
browser = await Browser.create(
self.connection, [], self.ignoreHTTPSErrors, self.defaultViewport,
self.proc, self.killChrome)
await self.ensureInitialPage(browser)
return browser
asyncio.get_event_loop().run_until_complete(self.killChrome())
# dont forget to close browser process
atexit.register(_close_process)
if self.options.get('handleSIGINT', True):
signal.signal(signal.SIGINT, _close_process)
if self.options.get('handleSIGTERM', True):
signal.signal(signal.SIGTERM, _close_process)
if not sys.platform.startswith('win'):
# SIGHUP is not defined on windows
if self.options.get('handleSIGHUP', True):
signal.signal(signal.SIGHUP, _close_process)
connectionDelay = self.options.get('slowMo', 0)
self.browserWSEndpoint = self._get_ws_endpoint()
self.connection = Connection(self.browserWSEndpoint, connectionDelay)
return await Browser.create(
self.connection, self.options, self.proc, self.killChrome)
def __init__(self, connection: Union[Connection, 'CDPSession'],
targetType: str, sessionId: str,
loop: asyncio.AbstractEventLoop) -> None:
"""Make new session."""
super().__init__()
self._lastId = 0
self._callbacks: Dict[int, asyncio.Future] = {}
self._connection: Optional[Connection] = connection
self._targetType = targetType
self._sessionId = sessionId
self._sessions: Dict[str, CDPSession] = dict()
self._loop = loop
async def launch(self):
self.chromeClosed = False
self.connection: Optional[Connection] = None
env = self.options.get('env')
self.proc = await asyncio.subprocess.create_subprocess_exec(
*self.cmd,
stdout=asyncio.subprocess.DEVNULL,
stderr=asyncio.subprocess.DEVNULL,
env=env,
)
def _close_process(*args, **kwargs):
if not self.chromeClosed:
asyncio.get_event_loop().run_until_complete(self.killChrome())
# dont forget to close browser process
atexit.register(_close_process)
if self.options.get('handleSIGINT', True):
signal.signal(signal.SIGINT, _close_process)
* ``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'))
asyncio.get_event_loop().run_until_complete(self.killChrome())
# dont forget to close browser process
atexit.register(_close_process)
if self.options.get("handleSIGINT", True):
signal.signal(signal.SIGINT, _close_process)
if self.options.get("handleSIGTERM", True):
signal.signal(signal.SIGTERM, _close_process)
if not sys.platform.startswith("win"):
# SIGHUP is not defined on windows
if self.options.get("handleSIGHUP", True):
signal.signal(signal.SIGHUP, _close_process)
connectionDelay = self.options.get("slowMo", 0)
self.browserWSEndpoint = self._get_ws_endpoint()
self.connection = Connection(self.browserWSEndpoint, connectionDelay)
return await Browser.create(
self.connection, self.options, self.proc, self.killChrome
)
async def launch(self) -> Browser: # noqa: C901
"""Start chrome process and return `Browser` object."""
self.chromeClosed = False
self.connection: Optional[Connection] = None
options = dict()
options['env'] = self.env
if not self.dumpio:
options['stdout'] = subprocess.PIPE
options['stderr'] = subprocess.STDOUT
self.proc = subprocess.Popen( # type: ignore
self.cmd,
**options,
)
def _close_process(*args: Any, **kwargs: Any) -> None:
if not self.chromeClosed:
self._loop.run_until_complete(self.killChrome())
def __patch_pyppeteer():
__logger.debug("Patching Pyppeteer.")
class PatchedConnection(connection.Connection):
def __init__(self, *args: Any, **kwargs: Any) -> None:
super().__init__(*args, **kwargs)
self._ws = websockets.client.connect(
self._url,
loop=self._loop,
max_size=None,
ping_interval=None,
ping_timeout=None,
)
connection.Connection = PatchedConnection
launcher.Connection = PatchedConnection
# endregion
def __patch_pyppeteer():
__logger.debug("Patching Pyppeteer.")
class PatchedConnection(connection.Connection):
def __init__(self, *args: Any, **kwargs: Any) -> None:
super().__init__(*args, **kwargs)
self._ws = websockets.client.connect(
self._url,
loop=self._loop,
max_size=None,
ping_interval=None,
ping_timeout=None,
)
connection.Connection = PatchedConnection
launcher.Connection = PatchedConnection
# endregion