python+playwright模拟手动输入
时间: 2023-06-13 11:05:06 浏览: 170
使用 Python playwright 模拟手动输入的方法如下:
1. 首先,导入 Playwright 的库和相关的模块:
```python
from playwright.sync_api import Playwright, sync_playwright
from playwright.sync_api import Keyboard
```
2. 然后创建一个 Playwright 的实例,并启动浏览器:
```python
with sync_playwright() as p:
browser = p.chromium.launch(headless=False)
page = browser.new_page()
```
3. 接下来,可以使用 `page.type()` 方法来模拟键盘输入,例如:
```python
page.type("#input-field", "Hello, World!")
```
上面的代码将在 id 为 `input-field` 的输入框中模拟输入 "Hello, World!"。
4. 如果需要按下特殊键,如回车键或删除键,可以使用 `page.keyboard.press()` 方法:
```python
page.keyboard.press("Enter")
```
5. 如果需要模拟多个按键的组合,例如 Ctrl+C,可以使用 `Keyboard` 类来实现:
```python
keyboard = page.keyboard
keyboard.press("Control")
keyboard.press("KeyC")
keyboard.up("Control")
```
上面的代码将模拟按下 Ctrl+C 的操作。
6. 最后,关闭浏览器:
```python
browser.close()
```
参考代码如下:
```python
from playwright.sync_api import Playwright, sync_playwright
from playwright.sync_api import Keyboard
with sync_playwright() as p:
browser = p.chromium.launch(headless=False)
page = browser.new_page()
page.goto("https://www.google.com")
page.type("input[name='q']", "Hello, World!")
page.keyboard.press("Enter")
browser.close()
```
上面的代码将在 Google 搜索中搜索 "Hello, World!" 并按下回车键。
阅读全文