当前位置:网站首页>Hello playwright: (7) simulate keyboard and mouse

Hello playwright: (7) simulate keyboard and mouse

2022-06-22 17:04:00 Dotnet cross platform

Although in the previous section , We have been able to pass FillAsync or ClickAsync To input and click elements . however , There are other scenes , We have to simulate the user using the keyboard 、 Mouse and page interaction . For example, online documents :

a959c9dc0a72af6bf2ecaca84d241175.png

Page.Keyboard object

Keyboard Provides... For managing virtual keyboards API, It will be page Generate the correct keydown、keypress and keyup event .

for example , Implement the following process :

  • Hold down Shift Key input characters a, Get capital letters A

  • Enter characters in actual case Bc

  • Hold down Shift Key not put , Press again 3 Second left arrow , Re release Shift key , Reach selected ABc Purpose

  • Input Backspace key , Delete selected text

  • Input text MyIO

The code is as follows :

await page.Keyboard.PressAsync("Shift+KeyA");
await page.Keyboard.TypeAsync("Bc");

await page.Keyboard.DownAsync("Shift");
for (var i = 0; i <3; i++)
    await page.Keyboard.PressAsync("ArrowLeft");
await page.Keyboard.UpAsync("Shift");

await page.Keyboard.PressAsync("Backspace");

await page.Keyboard.InsertTextAsync("MyIO");

6182555720e8a61cc870a0ed8c430a5b.gif

It's used here 3 Different input methods :

  • PressAsync, Enter a single character , Can and modifier keys ( for example Shiift) Use a combination of

  • TypeAsync, Enter individual characters one by one

  • InsertTextAsync, Input text , What's special is that it doesn't trigger keydown, keyup perhaps keypress event

Page.Mouse object

Mouse Provides for managing the virtual mouse API, The origin coordinate is page MainFrame The upper left corner of the view .

for example , Implement the following process :

  • Move the mouse to " more " link

  • Right click " translate " Icon

The code is as follows :

var moreLink = page.Locator("//*[@id=\"s-top-left\"]/div");
var box = await moreLink.BoundingBoxAsync();
await page.Mouse.MoveAsync(box.X , box.Y );

var moreDiv = page.Locator("id=s-top-more");
box = await moreDiv.BoundingBoxAsync();
await page.Mouse.ClickAsync(box.X + (box.Width / 3 / 2), box.Y + (box.
Height / 3 / 2), new MouseClickOptions { Button = MouseButton.Right });

3d4b619b7e1ca9919d8536f4841824c3.gif

Here we use a little trick , There is no need to guess " more " Where the link is located .Locator There's a name BoundingBoxAsync Methods , It returns the position of the element (X and Y) And size ( Width and height ).

By the location and size of the element , We can precisely control the mouse position , And there's no need to worry about UI Different resolutions interfere with operation .

Add microsignals 【MyIO666】, Invite you to join the technical exchange group

原网站

版权声明
本文为[Dotnet cross platform]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/173/202206221536306927.html