前言
在我们进行web自动化测试的过程中,我们经常会面临需要登录的情况,每一次打开页面如果都需要重新登录的话,就会大大增加测试所需要的时间,体现不出自动化测试的优势,我们都知道selenium可以通过cookie实现登录,那么playwright能不能实现这个功能呢?
答案是肯定的,playwright可以实现保存cookie实现自动化登录的功能。
获取保存cookie
我们以登录GitHub网站为例,登录代码如下:
from playwright.sync_api import Playwright, sync_playwright
def run(playwright: Playwright) -> None:
browser = playwright.chromium.launch(headless=False)
context = browser.new_context()
page = context.new_page()
page.goto('https://github.com/login')
# Interact with login form
page.get_by_label("Username or email address").fill("xxxxxxxxxxxxx")
page.get_by_label("Password").fill("xxxxxxxxxxxxx")
page.get_by_role("button", name="Sign in").click()
t
with sync_playwright() as playwright:
run(playwright)
我们可以实现GitHub网站的登录,登录之后我们需要保存我们的cookie信息,便于我们后续的登录操作,playwright提供了Context.storageState([options])方法用于保存cookie信息,代码如下:
from playwright.sync_api import Playwright, sync_playwright
def run(playwright: Playwright) -> None:
browser = playwright.chromium.launch(headless=False)
context = browser.new_context()
page = context.new_page()
page.goto('https://github.com/login')
# Interact with login form
page.get_by_label("Username or email address").fill("xxxxxxxxxxxxx")
page.get_by_label("Password").fill("xxxxxxxxxxx")
page.get_by_role("button", name="Sign in").click()
# Continue with the test
# # 保存storage state 到指定的文件
# storage = context.storage_state(path="cookie.json")
# ---------------------
context.close()
browser.close()
with sync_playwright() as playwright:
run(playwright)
我们可以看到我们的文件中生成了一个cookie.json文件,我们可以在其他地方使用这个cookie用于登录,现在我们来测试cookie是否能够使用这个cookie实现登录。
登录
我们使用cookie来登录,使用方法如下:
# Create a new context with the saved storage state.
context = browser.new_context(storage_state="state.json")
我们来登录GitHub试一下能否登录。
from playwright.sync_api import Playwright, sync_playwright, expect
def run(playwright: Playwright) -> None:
browser = playwright.chromium.launch(headless=False)
# 加载本地cookies,免登陆
context = browser.new_context(storage_state="cookie.json")
# 打开页面继续操作
page = context.new_page()
page.goto('https://github.com/')
page.pause() # 打断点看是不是已经登录了
context.close()
browser.close()
with sync_playwright() as playwright:
run(playwright)
总结
本文主要讲解了使用playwright,通过保存的cookie登录网站的操作步骤,与selenium类似,playwright也支持使用cookie登录,使我们的测试工作更加快速。