os: win11 mamba:v2.5.0
准备:安装Node.js;若已有 Node.js 版本的 Playwright,Python 版本需要独立安装浏览器内核,两者互不通用。
1. 创建独立沙盒,并初始化playwright conda环境
mamba conda create -n playwright-sandbox python=3.10.19 -y
mamba activate playwright-sandbox
python -m pip install --upgrade pip
pip install playwright 仅仅是安装了 Python 的控制库(相当于遥控器),它并不包含浏览器本身。
推荐pytest官网提供方式如下:自动把 pytest 和 playwright 作为依赖一并安装或升级
pip install pytest-playwright -i https://mirrors.ustc.edu.cn/pypi/simple
安装浏览器
playwright install # 该命令'秒退'了,是因为执行该命令首先去检查缓存目录:%USERPROFILE%\AppData\Local\ms-playwright 是否存在与当前 Python 库版本(比如 1.59.0)对应的浏览器二进制文件
playwright目录一览
playwright-demo/
├── tests/ # 存放录制的 Python/TS 脚本
│ ├── login.py
│ └── search.py
├── node_modules/ # Node.js 依赖(现有的)
├── package.json # Node.js 配置(现有的)
├── venv/ 或 .conda_env/ # playwright-sandbox 沙箱环境文件夹(建议加入 .gitignore)
└── requirements.txt # Python 依赖(记录 playwright==1.59.0 等)
2. 脚本录制
两种python脚本录制方式:
(1)npx playwright codegen --target python -o tests/search.py https://www.baidu.com # 录制异步脚本,须加上 --target python-async
(2)python -m playwright codegen -o tests/test.py https://example.com
codegen 只能录制单一线性的操作流程。如果想实现并行,比如同时打开多个网页进行操作(比如同时登录两个账号),这通常是在异步模式下配合 asyncio.gather 来实现的:
(1)先用 codegen 录制好单个任务的异步脚本。
(2)手动修改代码,将单任务封装成函数,然后用 asyncio.gather 同时触发。