menu Chancel's blog
rss_feed
Chancel's blog
有善始者实繁,能克终者盖寡。

Playwright入门指南

作者:Chancel Yang, 创建:2023-03-28, 字数:4293, 已阅:278, 最后更新:2023-03-28

这篇文章更新于 331 天前,文中部分信息可能失效,请自行甄别无效内容。

playwright是微软开源的自动化web应用程序测试框架,支持主流的PythonNodeJSJava等语言,官方文档已经非常完善了,本文将快速分享一些生产开发中常见的用法

1. 安装

接下来使用的Python版本是3.8.6

Windows7最高支持到3.8.10版本,考虑到兼容性则尽量使用3.8.10以下版本

使用pip安装playwright如下

pip3 install playwright
playwright install

例子一:使用传统的同步写法

from playwright.sync_api import sync_playwright

with sync_playwright() as p:
    browser = p.chromium.launch()
    page = browser.new_page()
    page.goto("http://playwright.dev")
    print(page.title())
    browser.close()

例子二:使用async/await异步语法

import asyncio
from playwright.async_api import async_playwright

async def main():
    async with async_playwright() as p:
        browser = await p.chromium.launch()
        page = await browser.new_page()
        await page.goto("http://playwright.dev")
        print(await page.title())
        await browser.close()

asyncio.run(main())

使用async能简单有效的提高并发,playwright在大部分场景下都属于网络IO密集型,但使用async写法对于开发人员的要求更高,同时debug也不如传统同步方法来的方便

是否使用异步写法取决于你的程序框架和开发需求

2. 使用

2.1. 元素选择

文档参考:https://playwright.dev/python/docs/api/class-locator

自动化测试非常需要的就是元素获取、元素点击、元素输入,下面以在bing.com搜索chancel.me并输出第一条搜索结果为例

from playwright.sync_api import sync_playwright

with sync_playwright() as p:
    b = p.chromium.launch()
    page = b.new_page()
    page.goto('https://bing.com')

    page.locator('#sb_form_q').fill('chancel.me') # fill方法填充字符串
    page.locator('#search_icon').click() # id选择并点击

    print(page.locator('[class=b_algo]').nth(0).text_content()) # class选择后获取文本

输出结果

syncmemo - Chancel's bloghttps://memo.chancel.me/help网页使用帮助 请记住本站网址 https://memo.chancel.me 使用步骤 访问本站时,会自动分配一个随机数(类似于97ND),请稍微花几秒钟记住这个ID,点击确认开始编辑便签内容

2.2. Cookies管理

文档参考:https://playwright.dev/python/docs/api/class-browsercontext

自动化通常会涉及到cookies保存,playwright获取Cookies需要创建新的context

以下是cookies的get/set操作例子

from playwright.sync_api import sync_playwright

cookies = None

with sync_playwright() as p:
    b = p.chromium.launch()
    c = b.new_context()
    page = c.new_page()
    page.goto('https://www.chancel.me/')
    cookies = c.cookies()

    print(cookies)

with sync_playwright() as p:
    b = p.chromium.launch()
    c = b.new_context()
    page = c.new_page()
    c.add_cookies(cookies)
    page.goto('https://www.chancel.me/')
    cookies = c.cookies()

    print(cookies)

输出结果

[{'name': 'TOKEN', 'value': 'c263e3a6-c88d-11ed-8979-6ee82343e005', 'domain': 'www.chancel.me', 'path': '/', 'expires': 1684658669.818441, 'httpOnly': True, 'secure': True, 'sameSite': 'Lax'}]

2.3. 文件下载

参考文档:https://playwright.dev/python/docs/api/class-download

以下载Github二进制包为例子

from playwright.sync_api import sync_playwright

cookies = None

with sync_playwright() as p:
    b = p.chromium.launch()
    page = b.new_page()
    page.goto('https://github.com/chancelyg/godaddy-ddns/releases')
    with page.expect_download() as download_info:
        page.locator('[href="/chancelyg/godaddy-ddns/releases/download/v23.01.06/godaddy-ddns_Darwin_arm64.tar.gz"]').click()
    download_info.value.save_as('godaddy-ddns_Darwin_arm64.tar.gz')

2.4. 页面录像与截图

参考文档:https://playwright.dev/python/docs/api/class-video

playwright开发时需要经常截图确认一下自动化流程是否正常,截图如下

from playwright.sync_api import sync_playwright

# 截图
with sync_playwright() as p:
    b = p.chromium.launch()
    page = b.new_page()
    page.goto('https://www.chancel.me')
    page.screenshot(path='screenshot.png')

# 录像
with sync_playwright() as p:
    b = p.chromium.launch()
    page = b.new_page(record_video_dir="videos", record_video_size={"width": 640, "height": 480})
    page.goto('https://www.google.com')
    page.goto('https://www.chancel.me')

3. Docker运行

参考文档:https://playwright.dev/docs/docker#image-tags

playwright有官方镜像,以mcr.microsoft.com/playwright/python:v1.31.0-focal为例,跑一个uvicorn网关应用的Dockerfile文件如下

FROM mcr.microsoft.com/playwright/python:v1.31.0-focal

ENV LANG en_US.UTF-8

WORKDIR /app

COPY ./web /app/web
COPY ./requirements.txt /app/requirements.txt


RUN pip3 install -r /app/requirements.txt && \
playwright install && \
ln -sf /usr/share/zoneinfo/Asia/Shanghai /etc/localtime


CMD ["uvicorn", "web:app", "--host=0.0.0.0", "--port=5000"]

[[replyMessage== null?"发表评论":"发表评论 @ " + replyMessage.m_author]]

account_circle
email
web_asset
textsms

评论列表([[messageResponse.total]])

还没有可以显示的留言...
[[messageItem.m_author]] [[messageItem.m_author]]
[[messageItem.create_time]]
[[getEnviron(messageItem.m_environ)]]
[[subMessage.m_author]] [[subMessage.m_author]] @ [[subMessage.parent_message.m_author]] [[subMessage.parent_message.m_author]]
[[subMessage.create_time]]
[[getEnviron(messageItem.m_environ)]]