1.pytest CLI参数
# 可以在浏览器上看到测试的执行
pytest --headed
# 无法在浏览器上看到测试的执行
pytest --headless
# 减慢浏览器的执行速度
pytest --slowmo=400
# 选择执行脚本的浏览器,默认是chrome
pytest --browser=firefox
pytest --browser=webkit
# 假设我们想要为我们的测试模拟一个设备,那么我们可以使用提供名称的设备参数,例如:我们设备的像素是5。
pytest --device="Pixel 5"
执行如图:
# enable tracing,我们可以提供三种不同的选择。
#
pytest --tracing on
pytest --tracing off
pytest --tracing retain-on-failure
#录屏
pytest --vedio on
#截图
pytest --screenshot on
pytest --screenshot only-on-failure
# 执行某个test case
pytest -k test_page_visit_docs
2. Python Debugger
2.1 使用breakpoint()
from playwright.sync_api import Page, expect
def test_page_has_get_started_link(page: Page):
page.goto("https://playwright.dev/python")
docs_link = page.get_by_role("link", name="GET STARTED")
expect(docs_link).to_be_visible()
def test_page_visits_docs(page: Page):
page.goto("https://playwright.dev/python")
link = page.get_by_role("link", name="GET STARTED")
breakpoint()
link.click()
expect(page).to_have_url("https://playwright.dev/python/docs/intro")
返回之前的页面page.go_back()
退出debug,继续执行下面的脚本continue
3. Device Emulation
from playwright.sync_api import Page, expect, sync_playwright
with sync_playwright() as playwright:
browser = playwright.chromium.launch(headless=False, slow_mo=500)
pixel_5_args = playwright.devices["Pixel 5"]
context = browser.new_context(**pixel_5_args)
page = context.new_page()
page.goto("https://playwright.dev/python")
link = page.get_by_role("link", name="GET STARTED")
link.click()
from playwright.sync_api import Page, expect, sync_playwright
with sync_playwright() as playwright:
browser = playwright.chromium.launch(headless=False, slow_mo=500)
context = browser.new_context(
viewport={
"width": 300,
"height": 500,
}
)
page = context.new_page()
page.goto("https://playwright.dev/python")
link = page.get_by_role("link", name="GET STARTED")
link.click()
如果想要在click之后,调整viewport size,可以在click后使用page.set_viewport_size()
:
page.set_viewport_size({
"width": 1000,
"height": 1000,
})
我们也可以使用ViewportSize实现上述功能。
from playwright.sync_api import ViewportSize
4. Javascript
使用JS滑动页面到最底部。
from playwright.sync_api import Page, expect, sync_playwright, ViewportSize
with sync_playwright() as playwright:
browser = playwright.chromium.launch(headless=False, slow_mo=500)
page = browser.new_page()
page.goto("https://playwright.dev/python")
page.evaluate("window.scrollBy(0, document.body.scrollHeight)")
page.screenshot(path="end.png")