Playwright is a powerful tool for automating browser actions such as clicks, keyboard input, and even complex mouse movements. It's available for JavaScript, Python, and other languages. In this post, we'll illustrate how to perform mouse actions using Playwright in JavaScript and Python.
JavaScript
In JavaScript, you can use the page.mouse
class to move the cursor and perform mouse clicks. Here's an example:
const { chromium } = require('playwright'); // Or 'firefox' or 'webkit'.
(async () => {
const browser = await chromium.launch();
const page = await browser.newPage();
await page.goto('http://example.com');
// Move the mouse to coordinates (100, 100) on the page.
await page.mouse.move(100, 100);
// Perform a left mouse button click.
await page.mouse.click(100, 100);
// Perform a right mouse button click.
await page.mouse.click(100, 100, { button: 'right' });
// Perform a double click.
await page.mouse.dblclick(100, 100);
await browser.close();
})();
Python
In Python, you can use the page.mouse
class for mouse movements and clicks. Here's an example:
from playwright.sync_api import sync_playwright
with sync_playwright() as p:
browser = p.chromium.launch()
page = browser.new_page()
page.goto('http://example.com')
# Move the mouse to coordinates (100, 100) on the page.
page.mouse.move(100, 100)
# Perform a left mouse button click.
page.mouse.click(100, 100)
# Perform a right mouse button click.
page.mouse.click(100, 100, button='right')
# Perform a double click.
page.mouse.dblclick(100, 100)
browser.close()
Remember, the coordinates (100, 100)
used in these examples are just for demonstration. You need to replace them with the actual coordinates on your web page.
Additional note:
If you want to perform complex mouse actions like drag and drop, you can do it by combining the move
, down
, and up
methods of the mouse
class.
For example, the following JavaScript code will drag an element from (startX, startY)
to (endX, endY)
:
await page.mouse.move(startX, startY);
await page.mouse.down();
await page.mouse.move(endX, endY);
await page.mouse.up();
The same can be achieved in Python as follows:
page.mouse.move(startX, startY)
page.mouse.down()
page.mouse.move(endX, endY)
page.mouse.up()
In these examples, replace startX
, startY
, endX
, and endY
with your actual coordinates.