API Reference¶
Commands¶
pyppeteer-install: Download and install chromium for pyppeteer.
Environment Variables¶
$PYPPETEER_HOME: Specify the directory to be used by pyppeteer. Pyppeteer uses this directory for extracting downloaded Chromium, and for making temporary user data directory. Default location depends on platform:Windows:
C:\Users\<username>\AppData\Local\pyppeteerOS X:
/Users/<username>/Library/Application Support/pyppeteerLinux:
/home/<username>/.local/share/pyppeteeror in
$XDG_DATA_HOME/pyppeteerif$XDG_DATA_HOMEis defined.
Details see appdirs‘s
user_data_dir.$PYPPETEER_DOWNLOAD_HOST: Overwrite host part of URL that is used to download Chromium. Defaults tohttps://storage.googleapis.com.$PYPPETEER_CHROMIUM_REVISION: Specify a certain version of chromium you’d like pyppeteer to use. Default value can be checked bypyppeteer.__chromium_revision__.$PYPPETEER_NO_PROGRESS_BAR: Suppress showing progress bar in chromium download process. Acceptable values are1ortrue(case-insensitive).
Pyppeteer Main Module¶
-
async
pyppeteer.launch(options: Optional[dict] = None, **kwargs: Any) → pyppeteer.browser.Browser[source]¶ Start chrome process and return
Browser. This function is a shortcut toLauncher(options, **kwargs).launch(). Available options are: *ignoreHTTPSErrors(bool): Whether to ignore HTTPS errors. Defaults toFalse.headless(bool): Whether to run browser in headless mode. Defaults toTrueunlessappModeordevtoolsoptions isTrue.executablePath(str): Path to a Chromium or Chrome executable to run instead of default bundled Chromium.slowMo(int|float): Slow down pyppeteer operations by the specified amount of milliseconds.defaultViewport(dict): Set a consistent viewport for each page. Defaults to an 800x600 viewport.Nonedisables default viewport. *width(int): page width in pixels. *height(int): page height in pixels. *deviceScaleFactor(int|float): Specify device scale factor (can bethought as dpr). Defaults to
1.isMobile(bool): Whether themeta viewporttag is taken into account. Defaults toFalse.hasTouch(bool): Specify if viewport supports touch events. Defaults toFalse.isLandscape(bool): Specify if viewport is in landscape mode. Defaults toFalse.
args(List[str]): Additional arguments (flags) to pass to the browser process.ignoreDefaultArgs(bool or List[str]): IfTrue, do not usedefaultArgs(). If list is given, then filter out given default arguments. Dangerous option; use with care. Defaults toFalse.handleSIGINT(bool): Close the browser process on Ctrl+C. Defaults toTrue.handleSIGTERM(bool): Close the browser process on SIGTERM. Defaults toTrue.handleSIGHUP(bool): Close the browser process on SIGHUP. Defaults toTrue.dumpio(bool): Whether to pipe the browser process stdout and stderr intoprocess.stdoutandprocess.stderr. Defaults toFalse.userDataDir(str): Path to a user data directory.env(dict): Specify environment variables that will be visible to the browser. Defaults to same as python process.devtools(bool): Whether to auto-open a DevTools panel for each tab. If this option isTrue, theheadlessoption will be setFalse.logLevel(int|str): Log level to print logs. Defaults to same as the root logger.autoClose(bool): Automatically close browser process when script completed. Defaults toTrue.loop(asyncio.AbstractEventLoop): Event loop (experimental).appMode(bool): Deprecated.
This function combines 3 steps: 1. Infer a set of flags to launch chromium with using
Launch browser and start managing its process according to the
executablePath,handleSIGINT,dumpio, and other options.Create an instance of
Browserclass and initialize it withdefaultViewport,slowMo, andignoreHTTPSErrors.
ignoreDefaultArgsoption can be used to customize behavior on the (1) step. For example, to filter out--mute-audiofrom default arguments: .. code:browser = await launch(ignoreDefaultArgs=['--mute-audio'])
Note
Pyppeteer can also be used to control the Chrome browser, but it works best with the version of Chromium it is bundled with. There is no guarantee it will work with any other version. Use
executablePathoption with extreme caution.
-
async
pyppeteer.connect(options: Optional[dict] = None, **kwargs: Any) → pyppeteer.browser.Browser[source]¶ Connect to the existing chrome.
browserWSEndpointorbrowserURLoption is necessary to connect to the chrome. The format ofbrowserWSEndpointisws://${host}:${port}/devtools/browser/<id>and format ofbrowserURLishttp://127.0.0.1:9222`. The value ofbrowserWSEndpointcan get bywsEndpoint. Available options are: *browserWSEndpoint(str): A browser websocket endpoint to connect to. *browserURL(str): A browser URL to connect to. *ignoreHTTPSErrors(bool): Whether to ignore HTTPS errors. Defaults toFalse.defaultViewport(dict): Set a consistent viewport for each page. Defaults to an 800x600 viewport.Nonedisables default viewport. *width(int): page width in pixels. *height(int): page height in pixels. *deviceScaleFactor(int|float): Specify device scale factor (can bethought as dpr). Defaults to
1.isMobile(bool): Whether themeta viewporttag is taken into account. Defaults toFalse.hasTouch(bool): Specify if viewport supports touch events. Defaults toFalse.isLandscape(bool): Specify if viewport is in landscape mode. Defaults toFalse.
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).
-
pyppeteer.defaultArgs(options: Optional[Dict] = None, **kwargs: Any) → List[str][source]¶ Get the default flags the chromium will be launched with.
optionsor keyword arguments are set of configurable options to set on the browser. Can have the following fields: *headless(bool): Whether to run browser in headless mode. Defaults toTrueunless thedevtoolsoption isTrue.args(List[str]): Additional arguments to pass to the browser instance. The list of chromium flags can be found here.userDataDir(str): Path to a User Data Directory.devtools(bool): Whether to auto-open DevTools panel for each tab. If this option isTrue, theheadlessoption will be setFalse.
Browser Class¶
-
class
pyppeteer.browser.Browser(connection: pyppeteer.connection.Connection, contextIds: List[str], ignoreHTTPSErrors: bool, defaultViewport: Optional[Dict], process: Optional[subprocess.Popen] = None, closeCallback: Optional[Callable[], Awaitable[None]]] = None, **kwargs: Any)[source]¶ Browser class.
A Browser object is created when pyppeteer connects to chrome, either through
launch()orconnect().-
property
browserContexts¶ Return a list of all open browser contexts.
In a newly created browser, this will return a single instance of
[BrowserContext]
-
property
process¶ Return process of this browser.
If browser instance is created by
pyppeteer.launcher.connect(), returnNone.
-
targets() → List[pyppeteer.target.Target][source]¶ Get a list of all active targets inside the browser.
In case of multiple browser contexts, the method will return a list with all the targets in all browser contexts.
-
property
wsEndpoint¶ Return websocket end point url.
-
property
BrowserContext Class¶
-
class
pyppeteer.browser.BrowserContext(browser: pyppeteer.browser.Browser, contextId: Optional[str])[source]¶ BrowserContext provides multiple independent browser sessions.
When a browser is launched, it has a single BrowserContext used by default. The method
browser.newPage()creates a page in the default browser context.If a page opens another page, e.g. with a
window.opencall, the popup will belong to the parent page’s browser context.Pyppeteer allows creation of “incognito” browser context with
browser.createIncognitoBrowserContext()method. “incognito” browser contexts don’t write any browser data to disk.# Create new incognito browser context context = await browser.createIncognitoBrowserContext() # Create a new page inside context page = await context.newPage() # ... do stuff with page ... await page.goto('https://example.com') # Dispose context once it's no longer needed await context.close()
-
property
browser¶ Return the browser this browser context belongs to.
-
isIncognite() → bool[source]¶ [Deprecated] Miss spelled method.
Use
isIncognito()method instead.
-
isIncognito() → bool[source]¶ Return whether BrowserContext is incognito.
The default browser context is the only non-incognito browser context.
Note
The default browser context cannot be closed.
-
targets() → List[pyppeteer.target.Target][source]¶ Return a list of all active targets inside the browser context.
-
property
Page Class¶
-
class
pyppeteer.page.Page(client: pyppeteer.connection.CDPSession, target: Target, frameTree: Dict, ignoreHTTPSErrors: bool, screenshotTaskQueue: list = None)[source]¶ Page class.
This class provides methods to interact with a single tab of chrome. One
Browserobject might have multiple Page object.The
Pageclass emits variousEventswhich can be handled by usingonoroncemethod, which is inherited from pyee’sEventEmitterclass.-
Events= namespace(Close='close', Console='console', Dialog='dialog', DOMContentLoaded='domcontentloaded', Error='error', PageError='pageerror', Request='request', Response='response', RequestFailed='requestfailed', RequestFinished='requestfinished', FrameAttached='frameattached', FrameDetached='framedetached', FrameNavigated='framenavigated', Load='load', Metrics='metrics', WorkerCreated='workercreated', WorkerDestroyed='workerdestroyed')¶ Available events.
-
property
browser¶ Get the browser the page belongs to.
-
property
frames¶ Get all frames of this page.
Change the default maximum navigation timeout.
This method changes the default timeout of 30 seconds for the following methods:
goto()goBack()goForward()reload()waitForNavigation()
- Parameters
timeout (int) – Maximum navigation time in milliseconds. Pass
0to disable timeout.
-
property
target¶ Return a target this page created from.
-
property
touchscreen¶ Get
Touchscreenobject.
-
property
tracing¶ Get tracing object.
-
property
url¶ Get URL of this page.
-
property
viewport¶ Get viewport as a dictionary or None.
Fields of returned dictionary is same as
setViewport().
-
waitFor(selectorOrFunctionOrTimeout: Union[str, int, float], options: Optional[dict] = None, *args: Any, **kwargs: Any) → Awaitable[source]¶ Wait for function, timeout, or element which matches on page.
This method behaves differently with respect to the first argument:
If
selectorOrFunctionOrTimeoutis 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
selectorOrFunctionOrTimeoutis a string of JavaScript function, this method is a shortcut towaitForFunction().If
selectorOrFunctionOrTimeoutis a selector string or xpath string, this method is a shortcut towaitForSelector()orwaitForXPath(). 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
waitForFunction()orwaitForSelector()directly.- Parameters
selectorOrFunctionOrTimeout – A selector, xpath, or function string, or timeout (milliseconds).
args (Any) – Arguments to pass the function.
- Returns
Return awaitable object which resolves to a JSHandle of the success value.
Available options: see
waitForFunction()orwaitForSelector()
-
waitForFunction(pageFunction: str, options: Optional[dict] = None, *args: str, **kwargs: Any) → Awaitable[source]¶ Wait until the function completes and returns a truthy value.
- Parameters
args (Any) – Arguments to pass to
pageFunction.- Returns
Return awaitable object which resolves when the
pageFunctionreturns a truthy value. It resolves to aJSHandleof the truthy value.
This method accepts the following options:
polling(str|number): An interval at which thepageFunctionis executed, defaults toraf. Ifpollingis a number, then it is treated as an interval in milliseconds at which the function would be executed. Ifpollingis a string, then it can be one of the following values:raf: to constantly executepageFunctioninrequestAnimationFramecallback. This is the tightest polling mode which is suitable to observe styling changes.mutation: to executepageFunctionon every DOM mutation.
timeout(int|float): maximum time to wait for in milliseconds. Defaults to 30000 (30 seconds). Pass0to disable timeout.
-
waitForSelector(selector: str, options: Optional[dict] = None, **kwargs: Any) → Awaitable[source]¶ Wait until element which matches
selectorappears on page.Wait for the
selectorto appear in page. If at the moment of calling the method theselectoralready exists, the method will return immediately. If the selector doesn’t appear after thetimeoutmilliseconds of waiting, the function will raise error.- Parameters
selector (str) – A selector of an element to wait for.
- Returns
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 havedisplay: noneorvisibility: hiddenCSS properties. Defaults toFalse.hidden(bool): Wait for element to not be found in the DOM or to be hidden, i.e. havedisplay: noneorvisibility: hiddenCSS properties. Defaults toFalse.timeout(int|float): Maximum time to wait for in milliseconds. Defaults to 30000 (30 seconds). Pass0to disable timeout.
-
waitForXPath(xpath: str, options: Optional[dict] = None, **kwargs: Any) → Awaitable[source]¶ Wait until element which matches
xpathappears on page.Wait for the
xpathto appear in page. If the moment of calling the method thexpathalready exists, the method will return immediately. If the xpath doesn’t appear aftertimeoutmilliseconds of waiting, the function will raise exception.- Parameters
xpath (str) – A [xpath] of an element to wait for.
- Returns
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 havedisplay: noneorvisibility: hiddenCSS properties. Defaults toFalse.hidden(bool): wait for element to not be found in the DOM or to be hidden, i.e. havedisplay: noneorvisibility: hiddenCSS properties. Defaults toFalse.timeout(int|float): maximum time to wait for in milliseconds. Defaults to 30000 (30 seconds). Pass0to disable timeout.
-
property
workers¶ Get all workers of this page.
-
Worker Class¶
-
class
pyppeteer.worker.Worker(client: CDPSession, url: str, consoleAPICalled: Callable[[str, List[pyppeteer.execution_context.JSHandle]], None], exceptionThrown: Callable[[Dict], None])[source]¶ The Worker class represents a WebWorker.
The events
workercreatedandworkerdestroyedare emitted on the page object to signal the worker lifecycle.page.on('workercreated', lambda worker: print('Worker created:', worker.url))
-
property
url¶ Return URL.
-
property
Keyboard Class¶
-
class
pyppeteer.input.Keyboard(client: pyppeteer.connection.CDPSession)[source]¶ Keyboard class provides as api for managing a virtual keyboard.
The high level api is
type(), which takes raw characters and generate proper keydown, keypress/input, and keyup events on your page.For finer control, you can use
down(),up(), andsendCharacter()to manually fire events as if they were generated from a real keyboard.An example of holding down
Shiftin order to select and delete some text:await page.keyboard.type('Hello, World!') await page.keyboard.press('ArrowLeft') await page.keyboard.down('Shift') for i in ' World': await page.keyboard.press('ArrowLeft') await page.keyboard.up('Shift') await page.keyboard.press('Backspace') # Result text will end up saying 'Hello!'.
An example of pressing
A:await page.keyboard.down('Shift') await page.keyboard.press('KeyA') await page.keyboard.up('Shift')
Mouse Class¶
-
class
pyppeteer.input.Mouse(client: pyppeteer.connection.CDPSession, keyboard: pyppeteer.input.Keyboard)[source]¶ Mouse class.
The
Mouseoperates in main-frame CSS pixels relative to the top-left corner of the viewport.
Tracing Class¶
-
class
pyppeteer.tracing.Tracing(client: pyppeteer.connection.CDPSession)[source]¶ Tracing class.
You can use
start()andstop()to create a trace file which can be opened in Chrome DevTools or timeline viewer.await page.tracing.start({'path': 'trace.json'}) await page.goto('https://www.google.com') await page.tracing.stop()
Dialog Class¶
-
class
pyppeteer.dialog.Dialog(client: pyppeteer.connection.CDPSession, type: str, message: str, defaultValue: str = '')[source]¶ Dialog class.
Dialog objects are dispatched by page via the
dialogevent.An example of using
Dialogclass:browser = await launch() page = await browser.newPage() async def close_dialog(dialog): print(dialog.message) await dialog.dismiss() await browser.close() page.on( 'dialog', lambda dialog: asyncio.ensure_future(close_dialog(dialog)) ) await page.evaluate('() => alert("1")')
-
property
defaultValue¶ If dialog is prompt, get default prompt value.
If dialog is not prompt, return empty string (
'').
-
property
message¶ Get dialog message.
-
property
type¶ Get dialog type.
One of
alert,beforeunload,confirm, orprompt.
-
property
ConsoleMessage Class¶
-
class
pyppeteer.page.ConsoleMessage(type: str, text: str, args: Optional[List[pyppeteer.execution_context.JSHandle]] = None)[source]¶ Console message class.
ConsoleMessage objects are dispatched by page via the
consoleevent.-
property
args¶ Return list of args (JSHandle) of this message.
-
property
text¶ Return text representation of this message.
-
property
type¶ Return type of this message.
-
property
Frame Class¶
-
class
pyppeteer.frame_manager.Frame(client: pyppeteer.connection.CDPSession, parentFrame: Optional[pyppeteer.frame_manager.Frame], frameId: str)[source]¶ Frame class.
Frame objects can be obtained via
pyppeteer.page.Page.mainFrame.-
property
childFrames¶ Get child frames.
-
property
name¶ Get frame name.
-
property
parentFrame¶ Get parent frame.
If this frame is main frame or detached frame, return
None.
-
property
url¶ Get url of the frame.
-
waitFor(selectorOrFunctionOrTimeout: Union[str, int, float], options: Optional[dict] = None, *args: Any, **kwargs: Any) → Union[Awaitable, pyppeteer.frame_manager.WaitTask][source]¶ Wait until
selectorOrFunctionOrTimeout.Details see
pyppeteer.page.Page.waitFor().
-
waitForFunction(pageFunction: str, options: Optional[dict] = None, *args: Any, **kwargs: Any) → pyppeteer.frame_manager.WaitTask[source]¶ Wait until the function completes.
Details see
pyppeteer.page.Page.waitForFunction().
-
waitForSelector(selector: str, options: Optional[dict] = None, **kwargs: Any) → pyppeteer.frame_manager.WaitTask[source]¶ Wait until element which matches
selectorappears on page.Details see
pyppeteer.page.Page.waitForSelector().
-
waitForXPath(xpath: str, options: Optional[dict] = None, **kwargs: Any) → pyppeteer.frame_manager.WaitTask[source]¶ Wait until element which matches
xpathappears on page.Details see
pyppeteer.page.Page.waitForXPath().
-
property
ExecutionContext Class¶
-
class
pyppeteer.execution_context.ExecutionContext(client: pyppeteer.connection.CDPSession, contextPayload: Dict, objectHandleFactory: Any, frame: Frame = None)[source]¶ Execution Context class.
-
property
frame¶ Return frame associated with this execution context.
-
property
JSHandle Class¶
-
class
pyppeteer.execution_context.JSHandle(context: pyppeteer.execution_context.ExecutionContext, client: pyppeteer.connection.CDPSession, remoteObject: Dict)[source]¶ JSHandle class.
JSHandle represents an in-page JavaScript object. JSHandle can be created with the
evaluateHandle()method.-
property
executionContext¶ Get execution context of this handle.
-
property
ElementHandle Class¶
-
class
pyppeteer.element_handle.ElementHandle(context: pyppeteer.execution_context.ExecutionContext, client: pyppeteer.connection.CDPSession, remoteObject: dict, page: Any, frameManager: FrameManager)[source]¶ ElementHandle class.
This class represents an in-page DOM element. ElementHandle can be created by the
pyppeteer.page.Page.querySelector()method.ElementHandle prevents DOM element from garbage collection unless the handle is disposed. ElementHandles are automatically disposed when their origin frame gets navigated.
ElementHandle isinstance can be used as arguments in
pyppeteer.page.Page.querySelectorEval()andpyppeteer.page.Page.evaluate()methods.-
asElement() → pyppeteer.element_handle.ElementHandle[source]¶ Return this ElementHandle.
-
Request Class¶
-
class
pyppeteer.network_manager.Request(client: pyppeteer.connection.CDPSession, requestId: Optional[str], interceptionId: Optional[str], isNavigationRequest: bool, allowInterception: bool, url: str, resourceType: str, payload: dict, frame: Optional[pyppeteer.frame_manager.Frame], redirectChain: List[pyppeteer.network_manager.Request])[source]¶ Request class.
Whenever the page sends a request, such as for a network resource, the following events are emitted by pyppeteer’s page:
'request': emitted when the request is issued by the page.'response': emitted when/if the response is received for the request.'requestfinished': emitted when the response body is downloaded and the request is complete.
If request fails at some point, then instead of
'requestfinished'event (and possibly instead of'response'event), the'requestfailed'event is emitted.If request gets a
'redirect'response, the request is successfully finished with the'requestfinished'event, and a new request is issued to a redirect url.-
failure() → Optional[Dict][source]¶ Return error text.
Return
Noneunless this request was failed, as reported byrequestfailedevent.When request failed, this method return dictionary which has a
errorTextfield, which contains human-readable error message, e.g.'net::ERR_RAILED'.
-
property
frame¶ Return a matching
frameobject.Return
Noneif navigating to error page.
-
property
headers¶ Return a dictionary of HTTP headers of this request.
All header names are lower-case.
Whether this request is driving frame’s navigation.
-
property
method¶ Return this request’s method (GET, POST, etc.).
-
property
postData¶ Return post body of this request.
-
property
redirectChain¶ Return chain of requests initiated to fetch a resource.
If there are no redirects and request was successful, the chain will be empty.
If a server responds with at least a single redirect, then the chain will contain all the requests that were redirected.
redirectChainis shared between all the requests of the same chain.
-
property
resourceType¶ Resource type of this request perceived by the rendering engine.
ResourceType will be one of the following:
document,stylesheet,image,media,font,script,texttrack,xhr,fetch,eventsource,websocket,manifest,other.
-
property
response¶ Return matching
Responseobject, orNone.If the response has not been received, return
None.
-
property
url¶ URL of this request.
Response Class¶
-
class
pyppeteer.network_manager.Response(client: pyppeteer.connection.CDPSession, request: pyppeteer.network_manager.Request, status: int, headers: Dict[str, str], fromDiskCache: bool, fromServiceWorker: bool, securityDetails: Optional[Dict] = None)[source]¶ Response class represents responses which are received by
Page.-
property
fromCache¶ Return
Trueif the response was served from cache.Here
cacheis either the browser’s disk cache or memory cache.
-
property
fromServiceWorker¶ Return
Trueif the response was served by a service worker.
-
property
headers¶ Return dictionary of HTTP headers of this response.
All header names are lower-case.
-
property
ok¶ Return bool whether this request is successful (200-299) or not.
-
property
securityDetails¶ Return security details associated with this response.
Security details if the response was received over the secure connection, or
Noneotherwise.
-
property
status¶ Status code of the response.
-
property
url¶ URL of the response.
-
property
Target Class¶
-
class
pyppeteer.target.Target(targetInfo: Dict, browserContext: BrowserContext, sessionFactory: Callable[], Coroutine[Any, Any, pyppeteer.connection.CDPSession]], ignoreHTTPSErrors: bool, defaultViewport: Optional[Dict], screenshotTaskQueue: List, loop: asyncio.events.AbstractEventLoop)[source]¶ Browser’s target class.
-
property
browser¶ Get the browser the target belongs to.
-
property
browserContext¶ Return the browser context the target belongs to.
-
property
opener¶ Get the target that opened this target.
Top-level targets return
None.
-
property
type¶ Get type of this target.
Type can be
'page','background_page','service_worker','browser', or'other'.
-
property
url¶ Get url of this target.
-
property
CDPSession Class¶
-
class
pyppeteer.connection.CDPSession(connection: Union[pyppeteer.connection.Connection, pyppeteer.connection.CDPSession], targetType: str, sessionId: str, loop: asyncio.events.AbstractEventLoop)[source]¶ Chrome Devtools Protocol Session.
The
CDPSessioninstances are used to talk raw Chrome Devtools Protocol:protocol methods can be called with
send()method.protocol events can be subscribed to with
on()method.
Documentation on DevTools Protocol can be found here.
Coverage Class¶
-
class
pyppeteer.coverage.Coverage(client: pyppeteer.connection.CDPSession)[source]¶ Coverage class.
Coverage gathers information about parts of JavaScript and CSS that were used by the page.
An example of using JavaScript and CSS coverage to get percentage of initially executed code:
# Enable both JavaScript and CSS coverage await page.coverage.startJSCoverage() await page.coverage.startCSSCoverage() # Navigate to page await page.goto('https://example.com') # Disable JS and CSS coverage and get results jsCoverage = await page.coverage.stopJSCoverage() cssCoverage = await page.coverage.stopCSSCoverage() totalBytes = 0 usedBytes = 0 coverage = jsCoverage + cssCoverage for entry in coverage: totalBytes += len(entry['text']) for range in entry['ranges']: usedBytes += range['end'] - range['start'] - 1 print('Bytes used: {}%'.format(usedBytes / totalBytes * 100))
Debugging¶
For debugging, you can set logLevel option to logging.DEBUG for
pyppeteer.launcher.launch() and pyppeteer.launcher.connect()
functions. However, this option prints too many logs including SEND/RECV
messages of pyppeteer. In order to only show suppressed error messages, you
should set pyppeteer.DEBUG to True.
Example:
import asyncio
import pyppeteer
from pyppeteer import launch
pyppeteer.DEBUG = True # print suppressed errors as error log
async def main():
browser = await launch()
... # do something
asyncio.get_event_loop().run_until_complete(main())