forked from microsoft/playwright-python
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path_browser.py
218 lines (196 loc) · 7.48 KB
/
_browser.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
# Copyright (c) Microsoft Corporation.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import base64
import json
from pathlib import Path
from types import SimpleNamespace
from typing import TYPE_CHECKING, Dict, List, Union
from playwright._impl._api_structures import (
Geolocation,
HttpCredentials,
ProxySettings,
StorageState,
ViewportSize,
)
from playwright._impl._browser_context import BrowserContext
from playwright._impl._cdp_session import CDPSession
from playwright._impl._connection import ChannelOwner, from_channel
from playwright._impl._helper import (
ColorScheme,
ReducedMotion,
is_safe_close_error,
locals_to_params,
)
from playwright._impl._network import serialize_headers
from playwright._impl._page import Page
if TYPE_CHECKING: # pragma: no cover
from playwright._impl._browser_type import BrowserType
class Browser(ChannelOwner):
Events = SimpleNamespace(
Disconnected="disconnected",
)
def __init__(
self, parent: "BrowserType", type: str, guid: str, initializer: Dict
) -> None:
super().__init__(parent, type, guid, initializer)
self._browser_type = parent
self._is_connected = True
self._is_closed_or_closing = False
self._is_remote = False
self._is_connected_over_websocket = False
self._contexts: List[BrowserContext] = []
self._channel.on("close", lambda _: self._on_close())
def __repr__(self) -> str:
return f"<Browser type={self._browser_type} version={self.version}>"
def _on_close(self) -> None:
self._is_connected = False
self.emit(Browser.Events.Disconnected, self)
self._is_closed_or_closing = True
@property
def contexts(self) -> List[BrowserContext]:
return self._contexts.copy()
def is_connected(self) -> bool:
return self._is_connected
async def new_context(
self,
viewport: ViewportSize = None,
screen: ViewportSize = None,
noViewport: bool = None,
ignoreHTTPSErrors: bool = None,
javaScriptEnabled: bool = None,
bypassCSP: bool = None,
userAgent: str = None,
locale: str = None,
timezoneId: str = None,
geolocation: Geolocation = None,
permissions: List[str] = None,
extraHTTPHeaders: Dict[str, str] = None,
offline: bool = None,
httpCredentials: HttpCredentials = None,
deviceScaleFactor: float = None,
isMobile: bool = None,
hasTouch: bool = None,
colorScheme: ColorScheme = None,
reducedMotion: ReducedMotion = None,
acceptDownloads: bool = None,
defaultBrowserType: str = None,
proxy: ProxySettings = None,
recordHarPath: Union[Path, str] = None,
recordHarOmitContent: bool = None,
recordVideoDir: Union[Path, str] = None,
recordVideoSize: ViewportSize = None,
storageState: Union[StorageState, str, Path] = None,
) -> BrowserContext:
params = locals_to_params(locals())
normalize_context_params(self._connection._is_sync, params)
channel = await self._channel.send("newContext", params)
context = from_channel(channel)
self._contexts.append(context)
context._browser = self
context._options = params
return context
async def new_page(
self,
viewport: ViewportSize = None,
screen: ViewportSize = None,
noViewport: bool = None,
ignoreHTTPSErrors: bool = None,
javaScriptEnabled: bool = None,
bypassCSP: bool = None,
userAgent: str = None,
locale: str = None,
timezoneId: str = None,
geolocation: Geolocation = None,
permissions: List[str] = None,
extraHTTPHeaders: Dict[str, str] = None,
offline: bool = None,
httpCredentials: HttpCredentials = None,
deviceScaleFactor: float = None,
isMobile: bool = None,
hasTouch: bool = None,
colorScheme: ColorScheme = None,
reducedMotion: ReducedMotion = None,
acceptDownloads: bool = None,
defaultBrowserType: str = None,
proxy: ProxySettings = None,
recordHarPath: Union[Path, str] = None,
recordHarOmitContent: bool = None,
recordVideoDir: Union[Path, str] = None,
recordVideoSize: ViewportSize = None,
storageState: Union[StorageState, str, Path] = None,
) -> Page:
params = locals_to_params(locals())
context = await self.new_context(**params)
page = await context.new_page()
page._owned_context = context
context._owner_page = page
return page
async def close(self) -> None:
if self._is_closed_or_closing:
return
self._is_closed_or_closing = True
try:
await self._channel.send("close")
except Exception as e:
if not is_safe_close_error(e):
raise e
if self._is_connected_over_websocket:
await self._connection.stop_async()
@property
def version(self) -> str:
return self._initializer["version"]
async def new_browser_cdp_session(self) -> CDPSession:
return from_channel(await self._channel.send("newBrowserCDPSession"))
async def start_tracing(
self,
page: Page = None,
path: Union[str, Path] = None,
screenshots: bool = None,
categories: List[str] = None,
) -> None:
params = locals_to_params(locals())
if page:
params["page"] = page._channel
if path:
params["path"] = str(path)
await self._channel.send("startTracing", params)
async def stop_tracing(self) -> bytes:
encoded_binary = await self._channel.send("stopTracing")
return base64.b64decode(encoded_binary)
def normalize_context_params(is_sync: bool, params: Dict) -> None:
params["sdkLanguage"] = "python" if is_sync else "python-async"
if params.get("noViewport"):
del params["noViewport"]
params["noDefaultViewport"] = True
if "defaultBrowserType" in params:
del params["defaultBrowserType"]
if "extraHTTPHeaders" in params:
params["extraHTTPHeaders"] = serialize_headers(params["extraHTTPHeaders"])
if "recordHarPath" in params:
params["recordHar"] = {"path": str(params["recordHarPath"])}
if "recordHarOmitContent" in params:
params["recordHar"]["omitContent"] = True
del params["recordHarOmitContent"]
del params["recordHarPath"]
if "recordVideoDir" in params:
params["recordVideo"] = {"dir": str(params["recordVideoDir"])}
if "recordVideoSize" in params:
params["recordVideo"]["size"] = params["recordVideoSize"]
del params["recordVideoSize"]
del params["recordVideoDir"]
if "storageState" in params:
storageState = params["storageState"]
if not isinstance(storageState, dict):
with open(storageState, "r") as f:
params["storageState"] = json.load(f)