LoginSignup
10
19

More than 1 year has passed since last update.

[Python]Playwright ブラウザ操作自動化 メモ

Posted at

Playwrightとは

  • Microsoft を中心に開発されているNode.js上からブラウザを操作するためのライブラリ。
  • 特徴
    • ブラウザ操作しながらテストコードを自動生成
    • クロスブラウザテストが可能
    • 対象ブラウザ:Chromium / Firefox / WebKit
    • Python以外にもNode.jsなど他言語にも対応

事前準備

  • インストール
  pip install --upgrade pip
  pip install playwright
  playwright install

コード生成

  • 次のコマンドを実行し、ブラウザ操作を行う。

    • Playwight PythonでGoogle検索を行い、検索結果の1番上のページにアクセスする場合
  playwright codegen google.com -o test_google.py

※操作後をブラウザを閉じることでコードが保存される。

  • 生成結果test_google.py
  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.google.com/?gws_rd=ssl
      page.goto("https://www.google.com/?gws_rd=ssl")

      # Go to https://www.google.com/search?q=Playwright+Python&oq=Playwright+Python&aqs=chrome..69i57.11242j0j4&sourceid=chrome&ie=UTF-8
      page.goto("https://www.google.com/search?q=Playwright+Python&oq=Playwright+Python&aqs=chrome..69i57.11242j0j4&sourceid=chrome&ie=UTF-8")

      # Click text=microsoft/playwright-python - GitHub
      page.click("text=microsoft/playwright-python - GitHub")
      # assert page.url == "https://github.com/microsoft/playwright-python"

      # Close page
      page.close()

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


  with sync_playwright() as playwright:
      run(playwright)

コード実行

  • ブラウザ操作の再実行
  python test_google.py
  • ヘッドレスモード実行したい場合
  # headless = False → True
  browser = playwright.chromium.launch(headless=True) 
  • Safari(Webkit)/Firefoxでの実行
  browser = playwright.webkit.launch(headless=False)
  # or
  browser = playwright.firefox.launch(headless=False)
  • スクリーンショット取得
  page.screenshot(path="./screenshot.png", full_page=True)

参考情報

10
19
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
10
19