Skip to content

Commit e9e8351

Browse files
authored
feat(sync): generate sync api (#78)
1 parent 4544fe4 commit e9e8351

File tree

15 files changed

+3031
-46
lines changed

15 files changed

+3031
-46
lines changed

client.py

Lines changed: 28 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -12,22 +12,28 @@
1212
# See the License for the specific language governing permissions and
1313
# limitations under the License.
1414

15-
import asyncio
15+
from playwright import chromium
1616

17-
from playwright import browser_types
1817

18+
def main() -> None:
19+
browser = chromium.launch(headless=False)
20+
page = browser.newPage(viewport=0)
21+
page.setContent(
22+
"<button id=button onclick=\"window.open('http://webkit.org', '_blank')\">Click me</input>"
23+
)
24+
25+
with page.expect_event("popup") as popup:
26+
page.click("#button")
27+
print(popup.value)
1928

20-
async def run() -> None:
21-
print("Launching browser...")
22-
browser = await browser_types["webkit"].launch(headless=False)
2329
print("Contexts in browser: %d" % len(browser.contexts))
2430
print("Creating context...")
25-
context = await browser.newContext(viewport=None)
31+
context = browser.newContext(viewport=0)
2632
print("Contexts in browser: %d" % len(browser.contexts))
2733
print("Pages in context: %d" % len(context.pages))
2834

2935
print("\nCreating page1...")
30-
page1 = await context.newPage()
36+
page1 = context.newPage()
3137
print("Pages in context: %d" % len(context.pages))
3238
page1.on("framenavigated", lambda frame: print("Frame navigated to %s" % frame.url))
3339
page1.on("request", lambda request: print("Request %s" % request.url))
@@ -42,42 +48,43 @@ async def run() -> None:
4248
),
4349
)
4450
print("Navigating page1 to https://example.com...")
45-
await page1.goto("https://example.com")
51+
page1.goto("https://example.com")
4652
print("Page1 main frame url: %s" % page1.mainFrame.url)
47-
print("Page1 tile: %s" % await page1.title())
53+
print("Page1 tile: %s" % page1.title())
4854
print("Frames in page1: %d" % len(page1.frames))
49-
await page1.screenshot(path="example.png")
55+
page1.screenshot(path="example.png")
5056

5157
print("\nCreating page2...")
52-
page2 = await context.newPage()
58+
page2 = context.newPage()
5359
page2.on("framenavigated", lambda frame: print("Frame navigated to %s" % frame.url))
5460

5561
print("Navigating page2 to https://webkit.org...")
56-
await page2.goto("https://webkit.org")
57-
print("Page2 tile: %s" % await page2.title())
62+
page2.goto("https://webkit.org")
63+
print("Page2 tile: %s" % page2.title())
5864
print("Pages in context: %d" % len(context.pages))
5965

6066
print("\nQuerying body...")
61-
body1 = await page1.querySelector("body")
67+
body1 = page1.querySelector("body")
6268
assert body1
63-
print("Body text %s" % await body1.textContent())
69+
print("Body text %s" % body1.textContent())
6470

6571
print("Closing page1...")
66-
await page1.close()
72+
page1.close()
6773
print("Pages in context: %d" % len(context.pages))
6874

6975
print("Navigating page2 to https://cnn.com...")
70-
await page2.goto("https://cnn.com")
76+
page2.goto("https://cnn.com")
7177
print("Page2 main frame url: %s" % page2.mainFrame.url)
72-
print("Page2 tile: %s" % await page2.title())
78+
print("Page2 tile: %s" % page2.title())
7379
print("Frames in page2: %d" % len(page2.frames))
7480
print("Pages in context: %d" % len(context.pages))
7581

7682
print("Closing context...")
77-
await context.close()
83+
context.close()
7884
print("Contexts in browser: %d" % len(browser.contexts))
7985
print("Closing browser")
80-
await browser.close()
86+
browser.close()
8187

8288

83-
asyncio.get_event_loop().run_until_complete(run())
89+
if __name__ == "__main__":
90+
main()

playwright/__init__.py

Lines changed: 9 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -14,19 +14,20 @@
1414

1515
import playwright.helper as helper
1616
from playwright._repo_version import version as __version__ # noqa:F401
17-
from playwright.main import playwright_object
17+
from playwright.main import playwright_async
18+
from playwright.sync import Playwright
1819

19-
chromium = playwright_object.chromium
20-
firefox = playwright_object.firefox
21-
webkit = playwright_object.webkit
22-
devices = playwright_object.devices
23-
selectors = playwright_object.selectors
24-
browser_types = playwright_object.browser_types
20+
playwright = Playwright(playwright_async)
21+
chromium = playwright.chromium
22+
firefox = playwright.firefox
23+
webkit = playwright.webkit
24+
devices = playwright.devices
25+
selectors = playwright.selectors
2526
Error = helper.Error
2627
TimeoutError = helper.TimeoutError
2728

2829
__all__ = [
29-
"browser_types",
30+
"playwright",
3031
"chromium",
3132
"firefox",
3233
"webkit",

playwright/accessibility.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@
1212
# See the License for the specific language governing permissions and
1313
# limitations under the License.
1414

15-
from typing import Dict
15+
from typing import Any, Dict
1616

1717
from playwright.connection import Channel
1818
from playwright.element_handle import ElementHandle
@@ -21,6 +21,7 @@
2121
class Accessibility:
2222
def __init__(self, channel: Channel) -> None:
2323
self._channel = channel
24+
self._sync_owner: Any = None
2425

2526
async def snapshot(
2627
self, interestingOnly: bool = True, root: ElementHandle = None

playwright/browser.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -86,7 +86,7 @@ async def newContext(
8686

8787
async def newPage(
8888
self,
89-
viewport: Dict = None,
89+
viewport: Union[Dict, Literal[0]] = None,
9090
ignoreHTTPSErrors: bool = None,
9191
javaScriptEnabled: bool = None,
9292
bypassCSP: bool = None,

playwright/connection.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -51,6 +51,7 @@ def __init__(
5151
is_scope: bool = False,
5252
) -> None:
5353
super().__init__()
54+
self._sync_owner: Any = None
5455
self._guid = guid
5556
self._scope = scope.create_child(guid) if is_scope else scope
5657
self._channel = Channel(self._scope, guid)

playwright/helper.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -44,7 +44,7 @@
4444
RouteHandler = Callable[["Route", "Request"], Any]
4545
FunctionWithSource = Callable[[Dict], Any]
4646

47-
ColorScheme = Literal["dark", "light", "no-preference"]
47+
ColorScheme = Literal["light", "dark", "no-preference"]
4848
DocumentLoadState = Literal["load", "domcontentloaded", "networkidle"]
4949
KeyboardModifier = Literal["Alt", "Control", "Meta", "Shift"]
5050
MouseButton = Literal["left", "right", "middle"]

playwright/input.py

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,13 +12,16 @@
1212
# See the License for the specific language governing permissions and
1313
# limitations under the License.
1414

15+
from typing import Any
16+
1517
from playwright.connection import Channel
1618
from playwright.helper import MouseButton, locals_to_params
1719

1820

1921
class Keyboard:
2022
def __init__(self, channel: Channel) -> None:
2123
self._channel = channel
24+
self._sync_owner: Any = None
2225

2326
async def down(self, key: str) -> None:
2427
await self._channel.send("keyboardDown", locals_to_params(locals()))
@@ -39,6 +42,7 @@ async def press(self, key: str, delay: int = None) -> None:
3942
class Mouse:
4043
def __init__(self, channel: Channel) -> None:
4144
self._channel = channel
45+
self._sync_owner: Any = None
4246

4347
async def move(self, x: float, y: float, steps: int = None) -> None:
4448
await self._channel.send("mouseMove", locals_to_params(locals()))

playwright/main.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -24,11 +24,11 @@
2424
from playwright.object_factory import create_remote_object
2525
from playwright.playwright import Playwright
2626

27-
playwright_object: Playwright
27+
playwright_async: Playwright
2828

2929

3030
async def async_init() -> None:
31-
global playwright_object
31+
global playwright_async
3232
package_path = os.path.dirname(os.path.abspath(__file__))
3333
platform = sys.platform
3434
if platform == "darwin":
@@ -66,7 +66,7 @@ async def async_init() -> None:
6666
connection = Connection(
6767
proc.stdout, proc.stdin, create_remote_object, asyncio.get_event_loop()
6868
)
69-
playwright_object = await connection.wait_for_object_with_known_name("playwright")
69+
playwright_async = await connection.wait_for_object_with_known_name("playwright")
7070

7171

7272
if sys.platform == "win32":

playwright/page.py

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -86,6 +86,9 @@ class Page(ChannelOwner):
8686
Popup="popup",
8787
Worker="worker",
8888
)
89+
accessibility: Accessibility
90+
keyboard: Keyboard
91+
mouse: Mouse
8992

9093
def __init__(self, scope: ConnectionScope, guid: str, initializer: Dict) -> None:
9194
super().__init__(scope, guid, initializer)
@@ -539,7 +542,7 @@ def isClosed(self) -> bool:
539542
async def click(
540543
self,
541544
selector: str,
542-
modifiers: KeyboardModifier = None,
545+
modifiers: List[KeyboardModifier] = None,
543546
position: Dict = None,
544547
delay: int = None,
545548
button: MouseButton = None,

playwright/playwright.py

Lines changed: 10 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -20,16 +20,19 @@
2020

2121

2222
class Playwright(ChannelOwner):
23+
chromium: BrowserType
24+
firefox: BrowserType
25+
webkit: BrowserType
26+
selectors: Selectors
27+
devices: Dict
28+
2329
def __init__(self, scope: ConnectionScope, guid: str, initializer: Dict) -> None:
2430
super().__init__(scope, guid, initializer)
25-
self.chromium: BrowserType = from_channel(initializer["chromium"])
26-
self.firefox: BrowserType = from_channel(initializer["firefox"])
27-
self.webkit: BrowserType = from_channel(initializer["webkit"])
28-
self.selectors: Selectors = from_channel(initializer["selectors"])
31+
self.chromium = from_channel(initializer["chromium"])
32+
self.firefox = from_channel(initializer["firefox"])
33+
self.webkit = from_channel(initializer["webkit"])
34+
self.selectors = from_channel(initializer["selectors"])
2935
self.devices = {
3036
device["name"]: device["descriptor"]
3137
for device in initializer["deviceDescriptors"]
3238
}
33-
self.browser_types: Dict[str, BrowserType] = dict(
34-
chromium=self.chromium, webkit=self.webkit, firefox=self.firefox
35-
)

0 commit comments

Comments
 (0)