/
_browser_type.py
245 lines (224 loc) · 8.47 KB
/
_browser_type.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
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
# 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 asyncio
import pathlib
from pathlib import Path
from typing import TYPE_CHECKING, Dict, List, Optional, Union, cast
from playwright._impl._api_structures import (
Geolocation,
HttpCredentials,
ProxySettings,
ViewportSize,
)
from playwright._impl._api_types import Error
from playwright._impl._browser import Browser, normalize_context_params
from playwright._impl._browser_context import BrowserContext
from playwright._impl._connection import (
ChannelOwner,
Connection,
from_channel,
from_nullable_channel,
)
from playwright._impl._helper import (
ColorScheme,
Env,
ForcedColors,
ReducedMotion,
locals_to_params,
)
from playwright._impl._transport import WebSocketTransport
from playwright._impl._wait_helper import throw_on_timeout
if TYPE_CHECKING:
from playwright._impl._playwright import Playwright
class BrowserType(ChannelOwner):
def __init__(
self, parent: ChannelOwner, type: str, guid: str, initializer: Dict
) -> None:
super().__init__(parent, type, guid, initializer)
_playwright: "Playwright"
def __repr__(self) -> str:
return f"<BrowserType name={self.name} executable_path={self.executable_path}>"
@property
def name(self) -> str:
return self._initializer["name"]
@property
def executable_path(self) -> str:
return self._initializer["executablePath"]
async def launch(
self,
executablePath: Union[str, Path] = None,
channel: str = None,
args: List[str] = None,
ignoreDefaultArgs: Union[bool, List[str]] = None,
handleSIGINT: bool = None,
handleSIGTERM: bool = None,
handleSIGHUP: bool = None,
timeout: float = None,
env: Env = None,
headless: bool = None,
devtools: bool = None,
proxy: ProxySettings = None,
downloadsPath: Union[str, Path] = None,
slowMo: float = None,
tracesDir: Union[pathlib.Path, str] = None,
chromiumSandbox: bool = None,
firefoxUserPrefs: Dict[str, Union[str, float, bool]] = None,
) -> Browser:
params = locals_to_params(locals())
normalize_launch_params(params)
browser = cast(
Browser, from_channel(await self._channel.send("launch", params))
)
browser._local_utils = self._playwright._utils
return browser
async def launch_persistent_context(
self,
userDataDir: Union[str, Path],
channel: str = None,
executablePath: Union[str, Path] = None,
args: List[str] = None,
ignoreDefaultArgs: Union[bool, List[str]] = None,
handleSIGINT: bool = None,
handleSIGTERM: bool = None,
handleSIGHUP: bool = None,
timeout: float = None,
env: Env = None,
headless: bool = None,
devtools: bool = None,
proxy: ProxySettings = None,
downloadsPath: Union[str, Path] = None,
slowMo: float = None,
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,
forcedColors: ForcedColors = None,
acceptDownloads: bool = None,
tracesDir: Union[pathlib.Path, str] = None,
chromiumSandbox: bool = None,
recordHarPath: Union[Path, str] = None,
recordHarOmitContent: bool = None,
recordVideoDir: Union[Path, str] = None,
recordVideoSize: ViewportSize = None,
baseURL: str = None,
strictSelectors: bool = None,
) -> BrowserContext:
userDataDir = str(Path(userDataDir))
params = locals_to_params(locals())
await normalize_context_params(self._connection._is_sync, params)
normalize_launch_params(params)
context = cast(
BrowserContext,
from_channel(await self._channel.send("launchPersistentContext", params)),
)
context._options = params
context.tracing._local_utils = self._playwright._utils
return context
async def connect_over_cdp(
self,
endpointURL: str,
timeout: float = None,
slow_mo: float = None,
headers: Dict[str, str] = None,
) -> Browser:
params = locals_to_params(locals())
response = await self._channel.send_return_as_dict("connectOverCDP", params)
browser = cast(Browser, from_channel(response["browser"]))
browser._local_utils = self._playwright._utils
default_context = cast(
Optional[BrowserContext],
from_nullable_channel(response.get("defaultContext")),
)
if default_context:
browser._contexts.append(default_context)
default_context._browser = browser
return browser
async def connect(
self,
ws_endpoint: str,
timeout: float = None,
slow_mo: float = None,
headers: Dict[str, str] = None,
) -> Browser:
if timeout is None:
timeout = 30000
headers = {**(headers if headers else {}), "x-playwright-browser": self.name}
transport = WebSocketTransport(
self._connection._loop, ws_endpoint, headers, slow_mo
)
connection = Connection(
self._connection._dispatcher_fiber,
self._connection._object_factory,
transport,
self._connection._loop,
)
connection.mark_as_remote()
connection._is_sync = self._connection._is_sync
connection._loop.create_task(connection.run())
playwright_future = connection.playwright_future
timeout_future = throw_on_timeout(timeout, Error("Connection timed out"))
done, pending = await asyncio.wait(
{transport.on_error_future, playwright_future, timeout_future},
return_when=asyncio.FIRST_COMPLETED,
)
if not playwright_future.done():
playwright_future.cancel()
if not timeout_future.done():
timeout_future.cancel()
playwright: "Playwright" = next(iter(done)).result()
playwright._set_selectors(self._playwright.selectors)
self._connection._child_ws_connections.append(connection)
pre_launched_browser = playwright._initializer.get("preLaunchedBrowser")
assert pre_launched_browser
browser = cast(Browser, from_channel(pre_launched_browser))
browser._should_close_connection_on_close = True
browser._local_utils = self._playwright._utils
def handle_transport_close() -> None:
for context in browser.contexts:
for page in context.pages:
page._on_close()
context._on_close()
browser._on_close()
connection.cleanup()
transport.once("close", handle_transport_close)
return browser
def normalize_launch_params(params: Dict) -> None:
if "env" in params:
params["env"] = [
{"name": name, "value": str(value)}
for [name, value] in params["env"].items()
]
if "ignoreDefaultArgs" in params:
if params["ignoreDefaultArgs"] is True:
params["ignoreAllDefaultArgs"] = True
del params["ignoreDefaultArgs"]
if "executablePath" in params:
params["executablePath"] = str(Path(params["executablePath"]))
if "downloadsPath" in params:
params["downloadsPath"] = str(Path(params["downloadsPath"]))