2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

Playwright自分メモ

Last updated at Posted at 2023-01-11

インストール(mac)

pip3 install playwright
python3 -m playwright install
pip3 install pytest-playwright
pip3 install pytest-xdist

サンプル生成

playwright codegen URL -o sample.py
playwright codegen URL -b firefox -o sample.py
playwright codegen URL -b webkit -o sample.py

基本

browser = playwright.chromium.launch(headless=True)
context = browser.new_context()
page = context.new_page()
page.goto(a_url)

インタラクティブに

from playwright.sync_api import sync_playwright

playwright = sync_playwright().start()
browser = playwright.chromium.launch(headless=False)
page = browser.new_page()
page.goto('https://google.com')

スクショを撮る

 page.screenshot(path="a.png")

特定の要素だけを撮る

page.locator("#some_id").screenshot(path="b.png")

htmlで保存

with open("a.html", 'w') as f:
  f.write(page.content())

タイムアウトさせない(無限に待つ)

page.set_default_timeout(0)

ブラウザのサイズ変更

page.set_viewport_size({"width": 4000, "height": 1000})

ファイル添付

page.locator("#hoge").set_input_files("some/file.csv")

こっちでも

page.locator("#hoge").set_input_files(files=[{"name": "empty.csv", "mimeType": "text/plain", "buffer": b",,,"}])

pytest

pip3 install pytest pytest-playwright
test.py
from playwright.sync_api import Playwright, sync_playwright, expect

def test_example_is_working(page):
    page.goto(URL)
    expect(page).to_have_title("hoge")
pytest --headed --screenshot=on --browser=chromium --browser=webkit --browser=firefox test.py

page を引数にすると、browserはpytestの引数で動き出す!

PWDEBUG=1 pytest test_hoge.py

で起動すると、インスペクターでデバッグできる

waitの使い分け

基本は

page.wait_for_load_state()

でよさそう。ajaxで画面が切り替わらず、通信する場合は

page.wait_for_load_state("networkidle")

で待つと良さそう

アサーション

expect(page.locator("#hoge")).to_have_text("fuga")

をよく見るが、to_have_textは完全一致っぽい。
正規表現もいける

expect(page.locator("#hoge")).to_have_text(re.compile(".*fuga.*"))

expect(page.locator("#hoge")).to_contain_text("fuga")

の方がシンプルで好き。

2
1
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
2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?