在python中,怎么用playwright处理已打开的网页
时间: 2023-12-27 16:05:29 浏览: 186
在Python中,可以使用Playwright的Python API来处理已经打开的网页。具体步骤如下:
1. 首先,需要安装playwright库,可以使用以下命令:
```python
pip install playwright
```
2. 导入playwright库,创建一个Browser对象,并打开一个页面:
```python
from playwright.sync_api import Playwright, sync_playwright
with sync_playwright() as p:
browser = p.chromium.launch()
page = browser.new_page()
page.goto('https://www.baidu.com')
```
3. 现在,我们已经打开了一个百度页面。可以通过Playwright的Python API来控制该页面。例如,我们可以获取页面的标题:
```python
title = page.title()
print(title)
```
4. 可以模拟用户操作,例如在搜索框中输入文本并点击搜索按钮:
```python
search_input = page.locator('#kw')
search_input.fill('Python')
search_button = page.locator('#su')
search_button.click()
```
5. 当我们完成了操作后,可以关闭浏览器:
```python
browser.close()
```
这就是使用Playwright处理已打开的网页的基本步骤。
阅读全文