Python自动化测试-自定义录制浏览器行为

Python自动化测试-自定义录制浏览器行为

我们可能在工作中遇到这样的需求,开机自启浏览器并在浏览器输入特定的IP进行访问,在Windows中很多人会使用bat批处理或者其他的脚本去做这件事情,但是比起更方便的可能是这个库了-Playwright!

Playwright是一个强大的Python库,仅用一个API即可自动执行Chromium、Firefox、WebKit等主流浏览器自动化操作,并同时支持以无头模式、有头模式运行。

Playwright提供的自动化技术是绿色的、功能强大、可靠且快速,支持Linux、Mac以及Windows操作系统。
Python自动化测试-自定义录制浏览器行为_第1张图片
Playwright的安装非常简单只有如下图所示的两步。实验环境Python3.7+。

#安装时间根据自己的网速 可能稍慢 大概十分钟左右
PS C:\Users\LENG> pip install playwright -i https://pypi.tuna.tsinghua.edu.cn/simple
Looking in indexes: https://pypi.tuna.tsinghua.edu.cn/simple
Collecting playwright
93a/playwright-0.162.2-py3-none-win_amd64.whl (54.5 MB)
     |████████████████████████████████| 54.5 MB 26 kB/s
Collecting pyee>=8.0.1
  Downloading https://pypi.tuna.tsinghua.edu.cn/packages/0d/0a/933b3931107e1da186963fd9bb9bceb9a613cff034cb0fb3b0c61003f357/pyee-8.1.0-py2.py3-none-any.whl (12 kB)
Collecting greenlet==1.0a1
     |████████████████████████████████| 94 kB 1.4 MB/s
Collecting typing-extensions
  Downloading https://pypi.tuna.tsinghua.edu.cn/packages/60/7a/e881b5abb54db0e6e671ab088d079c57ce54e8a01a3ca443f561ccadb37e/typing_extensions-3.7.4.3-py3-none-any.whl (22 kB)
Installing collected packages: pyee, greenlet, typing-extensions, playwright
  Attempting uninstall: pyee
    Found existing installation: pyee 7.0.1
    Uninstalling pyee-7.0.1:
      Successfully uninstalled pyee-7.0.1
Successfully installed greenlet-1.0a1 playwright-0.162.2 pyee-8.1.0 typing-extensions-3.7.4.3
WARNING: You are using pip version 20.2.2; however, version 20.3.1 is available.
You should consider upgrading via the 'c:\users\leng\appdata\local\programs\python\python37\python.exe -m pip install --upgrade pip' command.
PS C:\Users\LENG> python -m playwright install
Downloading chromium v827102 - 89.4 Mb [====================] 100% 0.0s
chromium v827102 downloaded to C:\Users\LENG\AppData\Local\ms-playwright\chromium-827102
Downloading firefox v1205 - 74.9 Mb [====================] 100% 0.0s
firefox v1205 downloaded to C:\Users\LENG\AppData\Local\ms-playwright\firefox-1205
Downloading webkit v1383 - 51.4 Mb [====================] 100% 0.0s
webkit v1383 downloaded to C:\Users\LENG\AppData\Local\ms-playwright\webkit-1383

Python自动化测试-自定义录制浏览器行为_第2张图片
使用Playwright无需写一行代码,我们只需手动操作浏览器,它会录制我们的操作,然后自动生成代码脚本。
下面就是录制的命令codegen,仅仅一行。

# 命令行键入 --help 可看到所有选项
python -m playwright codegen

键入上面命令会弹出一个前面下好的浏览器,然后只需要在浏览器中输入想要搜索的内容即可在对应的命令行终端中生成相应的代码。然后将生成的代码保存后下次运行代码就可以实现之前录制的操作。

from playwright import sync_playwright

def run(playwright):
    browser = playwright.chromium.launch(headless=False)
    context = browser.newContext()

    # Open new page
    page = context.newPage()

    # Go to https://www.baidu.com/
    page.goto("https://www.baidu.com/")

    # Click input[name="wd"]
    page.click("input[name=\"wd\"]")

    # Fill input[name="wd"]
    # with page.expect_navigation(url="https://www.baidu.com/s?ie=utf-8&f=8&rsv_bp=1&rsv_idx=1&tn=baidu&wd=你好世界&fenlei=256&rsv_pq=e6c1a3d20004f669&rsv_t=502eLSlJZF+Zxg16lsEvVaJnsqerAq+5tT52HSrGxBaQShLWdEmYiRKwa4w&rqlang=cn&rsv_enter=1&rsv_dl=tb&rsv_sug3=14&rsv_sug1=11&rsv_sug7=100&rsv_sug2=0&rsv_btype=i&prefixsug=%E4%BD%A0%E5%A5%BD%E4%B8%96%E7%95%8C&rsp=5&inputT=4193&rsv_sug4=4330"):
    with page.expect_navigation():
        page.fill("input[name=\"wd\"]", "你好世界")

    # ---------------------
    context.close()
    browser.close()

with sync_playwright() as playwright:
    run(playwright)

同步

下面示例代码:依次打开三个浏览器,前往baidu搜索,截图后退出。

from playwright import sync_playwright

with sync_playwright() as p:
    for browser_type in [p.chromium, p.firefox, p.webkit]:
        browser = browser_type.launch()
        page = browser.newPage()
        page.goto('https://baidu.com/')
        page.screenshot(path=f'example-{browser_type.name}.png')
        browser.close()

异步

异步操作可结合asyncio同时进行三个浏览器操作。

import asyncio
from playwright import async_playwright

async def main():
    async with async_playwright() as p:
        for browser_type in [p.chromium, p.firefox, p.webkit]:
            browser = await browser_type.launch()
            page = await browser.newPage()
            await page.goto('http://baidu.com/')
            await page.screenshot(path=f'example-{browser_type.name}.png')
            await browser.close()

asyncio.get_event_loop().run_until_complete(main())

GitHub链接:https://github.com/microsoft/playwright-python

你可能感兴趣的:(Python,自动化测试,Playwright)