Python Playwright 基本使用(步骤详细)

Python Playwright 基本使用(步骤详细)

js环境下,有 puppeteer 可以直接调用浏览器,使其实现自动化操作

在python环境下,则有类似的工具pyppeteer,然后此工具似乎不再维护。

优势

puppeteer 的使用是通过 Driver,控制 chrome浏览器实现自定义行为,这种控制针对每个浏览器的版本号,有对应的驱动

Playwright 中, 这种操作是基于开发者工具的,本身浏览器支持 f12 对网页进行调试。

安装

pip install playwright

然后需要使用 playwright 下载chrome浏览器

# 方式一:全装,会在当前 python 版本中
$ python -m playwright install

# 方式二:只安装 chromium,会在当前 python 版本中
$ python -m playwright install chromium

# 方式三:只安装 chromium,只会在当前项目中
# 按需安装,重新安装一下(chromium 是其中一个浏览器插件,看自己用什么就装什么) # Expecting one of: chromium, chrome, chrome-beta, msedge, msedge-beta, msedge-dev, firefox, webkit 
# PLAYWRIGHT_BROWSERS_PATH=0 是为了支持 pyinstaller 打包报错 Please run the following command to download new browsers 问题
# PLAYWRIGHT_BROWSERS_PATH=0 会让浏览器安装在项目本地的 `.playwright` 目录中,而不会使用全局的 Playwright 浏览器安装目录。
$ PLAYWRIGHT_BROWSERS_PATH=0 python -m playwright install chromium

# 通过《方式三》安装后,需要指定一下浏览器插件路径,要不然会报错,可以通过卸载获得安装路径,在重新安装一遍就行。
$ PLAYWRIGHT_BROWSERS_PATH=0 python -m playwright uninstall chromium

作者:卡尔特斯
链接:https://juejin.cn/post/7167303115984044040
来源:稀土掘金
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

需要注意的是,如果要将自己的项目,打包发布,那么建议使用第三种方式。
如果使用方式3安装 chrome。在使用时也需要注意:

from playwright.sync_api import Playwright, sync_playwright

# 如果是《方式三》安装的,需要指定路径
# chromium_path = "xxxxx/chromium-<version>/chrome-mac/Chromium.app/Contents/MacOS/Chromium"

# 创建浏览器
def run (playwright: Playwright) -> None:
    # 创建浏览器
    browser = playwright.chromium.launch(headless=False)
    # 如果通过《方式三》创建的,需要指定一下路径,要不然会找不到
    # browser = playwright.chromium.launch(executable_path=chromium_path, headless=False)

在代码中,创建启动 playwright 时,需要通过参数 executable_path 指定 chrome安装路径。

简易使用教程

参考:https://juejin.cn/post/7167303115984044040

优势

相比于 nodejs 的 puppeteer,这种方式无需驱动,显然兼容性更好

Copyright: 采用 知识共享署名4.0 国际许可协议进行许可

Links: https://zwc365.com/2025/04/13/pythonplaywright基本使用步骤详细

Buy me a cup of coffee ☕.