forked from microsoft/playwright-python
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path_browser.py
More file actions
272 lines (247 loc) · 9.43 KB
/
_browser.py
File metadata and controls
272 lines (247 loc) · 9.43 KB
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
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
# 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.
from pathlib import Path
from types import SimpleNamespace
from typing import (
TYPE_CHECKING,
Dict,
List,
Optional,
Pattern,
Sequence,
Set,
Union,
cast,
)
from playwright._impl._api_structures import (
ClientCertificate,
Geolocation,
HttpCredentials,
ProxySettings,
StorageState,
ViewportSize,
)
from playwright._impl._artifact import Artifact
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._errors import is_target_closed_error
from playwright._impl._helper import (
ColorScheme,
Contrast,
ForcedColors,
HarContentPolicy,
HarMode,
ReducedMotion,
ServiceWorkersPolicy,
locals_to_params,
make_dirs_for_file,
)
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._should_close_connection_on_close = False
self._cr_tracing_path: Optional[str] = None
self._contexts: Set[BrowserContext] = set()
self._traces_dir: Optional[str] = None
self._channel.on(
"context",
lambda params: self._did_create_context(
cast(BrowserContext, from_channel(params["context"]))
),
)
self._channel.on("close", lambda _: self._on_close())
self._close_reason: Optional[str] = None
def __repr__(self) -> str:
return f"<Browser type={self._browser_type} version={self.version}>"
def _connect_to_browser_type(
self,
browserType: "BrowserType",
tracesDir: Optional[str] = None,
) -> None:
# Note: when using connect(), `browserType` is different from `this.parent`.
# This is why browser type is not wired up in the constructor, and instead this separate method is called later on.
self._browser_type = browserType
self._traces_dir = tracesDir
for context in self._contexts:
self._setup_browser_context(context)
def _did_create_context(self, context: BrowserContext) -> None:
context._browser = self
self._contexts.add(context)
# Note: when connecting to a browser, initial contexts arrive before `_browserType` is set,
# and will be configured later in `ConnectToBrowserType`.
if self._browser_type:
self._setup_browser_context(context)
def _setup_browser_context(self, context: BrowserContext) -> None:
context._tracing._traces_dir = self._traces_dir
print("Appending context to selectors")
self._browser_type._playwright.selectors._contextsForSelectors.add(context)
def _on_close(self) -> None:
self._is_connected = False
self.emit(Browser.Events.Disconnected, self)
@property
def contexts(self) -> List[BrowserContext]:
return list(self._contexts)
@property
def browser_type(self) -> "BrowserType":
return self._browser_type
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: Sequence[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,
forcedColors: ForcedColors = None,
contrast: Contrast = 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,
baseURL: str = None,
strictSelectors: bool = None,
serviceWorkers: ServiceWorkersPolicy = None,
recordHarUrlFilter: Union[Pattern[str], str] = None,
recordHarMode: HarMode = None,
recordHarContent: HarContentPolicy = None,
clientCertificates: List[ClientCertificate] = None,
) -> BrowserContext:
params = locals_to_params(locals())
await self._browser_type._prepare_browser_context_params(params)
channel = await self._channel.send("newContext", params)
context = cast(BrowserContext, from_channel(channel))
await context._initialize_har_from_options(
record_har_content=recordHarContent,
record_har_mode=recordHarMode,
record_har_omit_content=recordHarOmitContent,
record_har_path=recordHarPath,
record_har_url_filter=recordHarUrlFilter,
)
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: Sequence[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,
forcedColors: ForcedColors = None,
contrast: Contrast = 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,
baseURL: str = None,
strictSelectors: bool = None,
serviceWorkers: ServiceWorkersPolicy = None,
recordHarUrlFilter: Union[Pattern[str], str] = None,
recordHarMode: HarMode = None,
recordHarContent: HarContentPolicy = None,
clientCertificates: List[ClientCertificate] = None,
) -> Page:
params = locals_to_params(locals())
async def inner() -> Page:
context = await self.new_context(**params)
page = await context.new_page()
page._owned_context = context
context._owner_page = page
return page
return await self._connection.wrap_api_call(inner)
async def close(self, reason: str = None) -> None:
self._close_reason = reason
try:
if self._should_close_connection_on_close:
await self._connection.stop_async()
else:
await self._channel.send("close", {"reason": reason})
except Exception as e:
if not is_target_closed_error(e):
raise e
@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: Sequence[str] = None,
) -> None:
params = locals_to_params(locals())
if page:
params["page"] = page._channel
if path:
self._cr_tracing_path = str(path)
params["path"] = str(path)
await self._channel.send("startTracing", params)
async def stop_tracing(self) -> bytes:
artifact = cast(Artifact, from_channel(await self._channel.send("stopTracing")))
buffer = await artifact.read_info_buffer()
await artifact.delete()
if self._cr_tracing_path:
make_dirs_for_file(self._cr_tracing_path)
with open(self._cr_tracing_path, "wb") as f:
f.write(buffer)
self._cr_tracing_path = None
return buffer