【python】Playwright基本用法


1. 官网

https://playwright.dev/docs/intro

2. github

https://github.com/microsoft/playwright-python

3. 安装

# 安装playwright库
pip install playwright

# 安装浏览器驱动文件(安装过程稍微有点慢)
python -m playwright install

4. 安装浏览器驱动,确实有点慢

PS E:\autotest> python -m playwright install
Downloading Playwright build of chromium v965416 - 102.8 Mb [==                  ] 9% 2128.1s

5. help

PS E:\autotest> playwright --help
Usage: playwright [options] [command]

Options:
  -V, --version                          output the version number
  -h, --help                             display help for command

Commands:
  open [options] [url]                   open page in browser specified via -b, --browser
  codegen [options] [url]                open page and generate code for user actions
  install [options] [browser...]         ensure browsers necessary for this version of Playwright are installed
  install-deps [options] [browser...]    install dependencies necessary to run browsers (will ask for sudo permissions)
  cr [options] [url]                     open page in Chromium
  ff [options] [url]                     open page in Firefox
  wk [options] [url]                     open page in WebKit
  screenshot [options]    capture a page screenshot
  pdf [options]           save page as pdf
  show-trace [options] [trace...]        Show trace viewer
  help [command]                         display help for command

6. codegen help

PS E:\autotest> python -m playwright codegen --help
Usage: playwright codegen [options] [url]

open page and generate code for user actions

Options:
  -o, --output      saves the generated script to a file
  --target           language to generate, one of javascript, test, python, python-async, csharp (default: "python")
  -b, --browser   browser to use, one of cr, chromium, ff, firefox, wk, webkit (default: "chromium")
  --channel           Chromium distribution channel, "chrome", "chrome-beta", "msedge-dev", etc
  --color-scheme       emulate preferred color scheme, "light" or "dark"
  --device         emulate device, for example  "iPhone 11"
  --geolocation   specify geolocation coordinates, for example "37.819722,-122.478611"
  --ignore-https-errors        ignore https errors
  --load-storage     load context storage state from the file, previously saved with --save-storage
  --lang             specify language / locale, for example "en-GB"
  --proxy-server        specify proxy server, for example "http://myproxy:3128" or "socks5://myproxy:8080"
  --proxy-bypass       comma-separated domains to bypass proxy, for example ".com,chromium.org,.domain.com"
  --save-storage     save context storage state at the end, for later use with --load-storage
  --save-trace       record a trace for the session and save it to a file
  --timezone <time zone>       time zone to emulate, for example "Europe/Rome"
  --timeout           timeout for Playwright actions in milliseconds (default: "10000")
  --user-agent      specify user agent string
  --viewport-size        specify browser viewport size in pixels, for example "1280, 720"
  -h, --help                   display help for command

Examples:

  $ codegen
  $ codegen --target=python
  $ codegen -b webkit https://example.com

6. 生成python脚本

python -m playwright codegen --target python -o 'baidu.py' -b chromium https://www.baidu.com

7. python脚本

from playwright.sync_api import Playwright, sync_playwright


def run(playwright: Playwright) -> None:
    browser = playwright.chromium.launch(headless=False)
    context = browser.new_context()

    # Open new page
    page = context.new_page()

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

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

    # Fill input[name="wd"]
    page.locator("input[name=\"wd\"]").fill("ewu")

    # Press Enter
    # with page.expect_navigation(url="https://www.baidu.com/s?ie=utf-8&f=3&rsv_bp=1&rsv_idx=1&tn=baidu&wd=%E4%BF%84%E4%B9%8C%E5%86%B2%E7%AA%81&fenlei=256&rsv_pq=bcbe1f630001b2d8&rsv_t=8815Rknx8geggPHol8NEtStIzoya5ssaRAwypM%2BIoJi48q15YIyXvmbOPAc&rqlang=cn&rsv_dl=ts_1&rsv_enter=1&rsv_sug3=10&rsv_sug1=11&rsv_sug7=100&rsv_sug2=0&rsv_btype=i&prefixsug=ewu&rsp=1&inputT=15942&rsv_sug4=19327&rsv_jmp=fail"):
    with page.expect_navigation():
        page.locator("input[name=\"wd\"]").press("Enter")
    # assert page.url == "https://www.baidu.com/s?ie=utf-8&f=3&rsv_bp=1&rsv_idx=1&tn=baidu&wd=%E4%BF%84%E4%B9%8C%E5%86%B2%E7%AA%81&fenlei=256&rsv_pq=bcbe1f630001b2d8&rsv_t=8815Rknx8geggPHol8NEtStIzoya5ssaRAwypM%2BIoJi48q15YIyXvmbOPAc&rqlang=cn&rsv_dl=ts_1&rsv_enter=1&rsv_sug3=10&rsv_sug1=11&rsv_sug7=100&rsv_sug2=0&rsv_btype=i&prefixsug=ewu&rsp=1&inputT=15942&rsv_sug4=19327"

    # Click text=俄乌局势 >> nth=0
    page.locator("text=俄乌局势").first.click()

    # Close page
    page.close()

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


with sync_playwright() as playwright:
    run(playwright)

参考链接:

https://juejin.cn/post/6906866546094637064

https://www.cnblogs.com/sanyvaelailai/p/14688189.html

https://www.testim.io/blog/puppeteer-selenium-playwright-cypress-how-to-choose/