_browser.py 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293
  1. # Copyright (c) Microsoft Corporation.
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. from pathlib import Path
  15. from types import SimpleNamespace
  16. from typing import (
  17. TYPE_CHECKING,
  18. Dict,
  19. List,
  20. Optional,
  21. Pattern,
  22. Sequence,
  23. Set,
  24. Union,
  25. cast,
  26. )
  27. from playwright._impl._api_structures import (
  28. BrowserBindResult,
  29. ClientCertificate,
  30. Geolocation,
  31. HttpCredentials,
  32. ProxySettings,
  33. StorageState,
  34. ViewportSize,
  35. )
  36. from playwright._impl._artifact import Artifact
  37. from playwright._impl._browser_context import BrowserContext
  38. from playwright._impl._cdp_session import CDPSession
  39. from playwright._impl._connection import ChannelOwner, from_channel
  40. from playwright._impl._errors import is_target_closed_error
  41. from playwright._impl._helper import (
  42. ColorScheme,
  43. Contrast,
  44. ForcedColors,
  45. HarContentPolicy,
  46. HarMode,
  47. ReducedMotion,
  48. ServiceWorkersPolicy,
  49. locals_to_params,
  50. make_dirs_for_file,
  51. )
  52. from playwright._impl._page import Page
  53. if TYPE_CHECKING: # pragma: no cover
  54. from playwright._impl._browser_type import BrowserType
  55. class Browser(ChannelOwner):
  56. Events = SimpleNamespace(
  57. Context="context",
  58. Disconnected="disconnected",
  59. )
  60. def __init__(
  61. self, parent: "BrowserType", type: str, guid: str, initializer: Dict
  62. ) -> None:
  63. super().__init__(parent, type, guid, initializer)
  64. self._browser_type: Optional["BrowserType"] = None
  65. self._is_connected = True
  66. self._should_close_connection_on_close = False
  67. self._cr_tracing_path: Optional[str] = None
  68. self._contexts: Set[BrowserContext] = set()
  69. self._traces_dir: Optional[str] = None
  70. self._channel.on(
  71. "context",
  72. lambda params: self._did_create_context(
  73. cast(BrowserContext, from_channel(params["context"]))
  74. ),
  75. )
  76. self._channel.on("close", lambda _: self._on_close())
  77. self._close_reason: Optional[str] = None
  78. def __repr__(self) -> str:
  79. return f"<Browser type={self._browser_type} version={self.version}>"
  80. def _connect_to_browser_type(
  81. self,
  82. browser_type: "BrowserType",
  83. traces_dir: Optional[str] = None,
  84. ) -> None:
  85. # Note: when using connect(), `browserType` is different from `this.parent`.
  86. # This is why browser type is not wired up in the constructor, and instead this separate method is called later on.
  87. self._browser_type = browser_type
  88. self._traces_dir = traces_dir
  89. for context in self._contexts:
  90. self._setup_browser_context(context)
  91. def _did_create_context(self, context: BrowserContext) -> None:
  92. context._browser = self
  93. self._contexts.add(context)
  94. # Note: when connecting to a browser, initial contexts arrive before `_browserType` is set,
  95. # and will be configured later in `ConnectToBrowserType`.
  96. if self._browser_type:
  97. self._setup_browser_context(context)
  98. self.emit(Browser.Events.Context, context)
  99. def _setup_browser_context(self, context: BrowserContext) -> None:
  100. context._tracing._traces_dir = self._traces_dir
  101. assert self._browser_type is not None
  102. self._browser_type._playwright.selectors._contexts_for_selectors.add(context)
  103. def _on_close(self) -> None:
  104. self._is_connected = False
  105. self.emit(Browser.Events.Disconnected, self)
  106. @property
  107. def contexts(self) -> List[BrowserContext]:
  108. return list(self._contexts)
  109. @property
  110. def browser_type(self) -> "BrowserType":
  111. assert self._browser_type is not None
  112. return self._browser_type
  113. def is_connected(self) -> bool:
  114. return self._is_connected
  115. async def new_context(
  116. self,
  117. viewport: ViewportSize = None,
  118. screen: ViewportSize = None,
  119. noViewport: bool = None,
  120. ignoreHTTPSErrors: bool = None,
  121. javaScriptEnabled: bool = None,
  122. bypassCSP: bool = None,
  123. userAgent: str = None,
  124. locale: str = None,
  125. timezoneId: str = None,
  126. geolocation: Geolocation = None,
  127. permissions: Sequence[str] = None,
  128. extraHTTPHeaders: Dict[str, str] = None,
  129. offline: bool = None,
  130. httpCredentials: HttpCredentials = None,
  131. deviceScaleFactor: float = None,
  132. isMobile: bool = None,
  133. hasTouch: bool = None,
  134. colorScheme: ColorScheme = None,
  135. reducedMotion: ReducedMotion = None,
  136. forcedColors: ForcedColors = None,
  137. contrast: Contrast = None,
  138. acceptDownloads: bool = None,
  139. defaultBrowserType: str = None,
  140. proxy: ProxySettings = None,
  141. recordHarPath: Union[Path, str] = None,
  142. recordHarOmitContent: bool = None,
  143. recordVideoDir: Union[Path, str] = None,
  144. recordVideoSize: ViewportSize = None,
  145. storageState: Union[StorageState, str, Path] = None,
  146. baseURL: str = None,
  147. strictSelectors: bool = None,
  148. serviceWorkers: ServiceWorkersPolicy = None,
  149. recordHarUrlFilter: Union[Pattern[str], str] = None,
  150. recordHarMode: HarMode = None,
  151. recordHarContent: HarContentPolicy = None,
  152. clientCertificates: List[ClientCertificate] = None,
  153. ) -> BrowserContext:
  154. params = locals_to_params(locals())
  155. assert self._browser_type is not None
  156. await self._browser_type._prepare_browser_context_params(params)
  157. channel = await self._channel.send("newContext", None, params)
  158. context = cast(BrowserContext, from_channel(channel))
  159. await context._initialize_har_from_options(
  160. record_har_content=recordHarContent,
  161. record_har_mode=recordHarMode,
  162. record_har_omit_content=recordHarOmitContent,
  163. record_har_path=recordHarPath,
  164. record_har_url_filter=recordHarUrlFilter,
  165. )
  166. return context
  167. async def new_page(
  168. self,
  169. viewport: ViewportSize = None,
  170. screen: ViewportSize = None,
  171. noViewport: bool = None,
  172. ignoreHTTPSErrors: bool = None,
  173. javaScriptEnabled: bool = None,
  174. bypassCSP: bool = None,
  175. userAgent: str = None,
  176. locale: str = None,
  177. timezoneId: str = None,
  178. geolocation: Geolocation = None,
  179. permissions: Sequence[str] = None,
  180. extraHTTPHeaders: Dict[str, str] = None,
  181. offline: bool = None,
  182. httpCredentials: HttpCredentials = None,
  183. deviceScaleFactor: float = None,
  184. isMobile: bool = None,
  185. hasTouch: bool = None,
  186. colorScheme: ColorScheme = None,
  187. forcedColors: ForcedColors = None,
  188. contrast: Contrast = None,
  189. reducedMotion: ReducedMotion = None,
  190. acceptDownloads: bool = None,
  191. defaultBrowserType: str = None,
  192. proxy: ProxySettings = None,
  193. recordHarPath: Union[Path, str] = None,
  194. recordHarOmitContent: bool = None,
  195. recordVideoDir: Union[Path, str] = None,
  196. recordVideoSize: ViewportSize = None,
  197. storageState: Union[StorageState, str, Path] = None,
  198. baseURL: str = None,
  199. strictSelectors: bool = None,
  200. serviceWorkers: ServiceWorkersPolicy = None,
  201. recordHarUrlFilter: Union[Pattern[str], str] = None,
  202. recordHarMode: HarMode = None,
  203. recordHarContent: HarContentPolicy = None,
  204. clientCertificates: List[ClientCertificate] = None,
  205. ) -> Page:
  206. params = locals_to_params(locals())
  207. async def inner() -> Page:
  208. context = await self.new_context(**params)
  209. page = await context.new_page()
  210. page._owned_context = context
  211. context._owner_page = page
  212. return page
  213. return await self._connection.wrap_api_call(inner, title="Create page")
  214. async def close(self, reason: str = None) -> None:
  215. self._close_reason = reason
  216. try:
  217. if self._should_close_connection_on_close:
  218. await self._connection.stop_async()
  219. else:
  220. await self._channel.send("close", None, {"reason": reason})
  221. except Exception as e:
  222. if not is_target_closed_error(e):
  223. raise e
  224. @property
  225. def version(self) -> str:
  226. return self._initializer["version"]
  227. async def new_browser_cdp_session(self) -> CDPSession:
  228. return from_channel(await self._channel.send("newBrowserCDPSession", None))
  229. async def bind(
  230. self,
  231. title: str,
  232. workspaceDir: str = None,
  233. host: str = None,
  234. port: int = None,
  235. ) -> BrowserBindResult:
  236. return await self._channel.send_return_as_dict(
  237. "startServer", None, locals_to_params(locals())
  238. )
  239. async def unbind(self) -> None:
  240. await self._channel.send("stopServer", None)
  241. async def start_tracing(
  242. self,
  243. page: Page = None,
  244. path: Union[str, Path] = None,
  245. screenshots: bool = None,
  246. categories: Sequence[str] = None,
  247. ) -> None:
  248. params = locals_to_params(locals())
  249. if page:
  250. params["page"] = page._channel
  251. if path:
  252. self._cr_tracing_path = str(path)
  253. params["path"] = str(path)
  254. await self._channel.send("startTracing", None, params)
  255. async def stop_tracing(self) -> bytes:
  256. artifact = cast(
  257. Artifact, from_channel(await self._channel.send("stopTracing", None))
  258. )
  259. buffer = await artifact.read_info_buffer()
  260. await artifact.delete()
  261. if self._cr_tracing_path:
  262. make_dirs_for_file(self._cr_tracing_path)
  263. with open(self._cr_tracing_path, "wb") as f:
  264. f.write(buffer)
  265. self._cr_tracing_path = None
  266. return buffer