1. 登录账号
以下以Google为例:
2. 保存身份验证状态
from creds import EMAIL, PASSWORD
from playwright.sync_api import sync_playwright
with sync_playwright() as playwright:
browser = playwright.firefox.launch(headless=False, slow_mo=500)
# Browser context will allow us to store the authentication state and save it when we have performed
context = browser.new_context()
page = context.new_page()
page.goto("https://accounts.google.com")
# Enter email
email_input = page.get_by_label("Email or phone")
email_input.fill(EMAIL)
next_btn = page.get_by_role("button", name="Next").click()
# Enter password
password_input = page.get_by_label("Enter your password")
password_input.fill(PASSWORD)
next_btn = page.get_by_role("button", name="Next").click()
page.pause()
# Save authentication state: recommend to create a folder to save our storage
# Create 2 folders: playwright\.auth
context.storage_state(path="playwright/.auth/storage_state.json")
context.close()
- 打开页面,输入用户名,点击Next
- 输入密码,点击Next
这时进入page.pause()
,因为需要一个验证码的手动验证
输入完成后关掉pause
执行结束之后,我们可以看到文件夹下面多了一个刚刚保存的文件。
3. 重复使用身份验证状态
修改part2的code,引用part 2 save的文件
from creds import EMAIL, PASSWORD
from playwright.sync_api import sync_playwright
with sync_playwright() as playwright:
browser = playwright.firefox.launch(headless=False, slow_mo=500)
# Browser context will allow us to store the authentication state and save it when we have performed
context = browser.new_context(
storage_state="playwright/.auth/storage_state.json"
)
page = context.new_page()
page.goto("https://accounts.google.com")
page.pause()
context.close()
执行code会直接登录,进入Home页