软件测试|web自动化测试神器playwright教程(十一)
【摘要】 前言在我们进行web自动化测试的过程中,我们经常会面临需要登录的情况,每一次打开页面如果都需要重新登录的话,就会大大增加测试所需要的时间,体现不出自动化测试的优势,我们都知道selenium可以通过cookie实现登录,那么playwright能不能实现这个功能呢?答案是肯定的,playwright可以实现保存cookie实现自动化登录的功能。 获取保存cookie我们以登录GitHub网...
前言
在我们进行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登录,使我们的测试工作更加快速。
【版权声明】本文为华为云社区用户原创内容,转载时必须标注文章的来源(华为云社区)、文章链接、文章作者等基本信息, 否则作者和本社区有权追究责任。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱:
cloudbbs@huaweicloud.com
- 点赞
- 收藏
- 关注作者
评论(0)