(1)同步函数
from playwright.sync_api import sync_playwright
doubanMovieURL = "https://movie.douban.com/"
with sync_playwright() as p:
browser = p.chromium.launch(headless=False)
page = browser.new_page()
page.goto(doubanMovieURL)
print(page.title())
browser.close()
(2) 异步函数
import asyncio
from playwright.async_api import async_playwright
doubanMovieURL = "https://movie.douban.com/"
async def main():
async with async_playwright() as p:
browser = await p.chromium.launch(headless=False)
page = await browser.new_page()
await page.goto(doubanMovieURL)
print(await page.title())
await browser.close()
asyncio.run(main())
(3) 录制代码
在terminal中输入:playwright codegen url
playwright codegen www.douban.com
(4) 保留经过身份验证的状态
playwright codegen --save-storage=auth.json
生成auth.json文件
保存好cookie后,执行以下代码,可以直接跳转至登录后的页面:
playwright open --load-storage=auth.json https://www.bizreach.jp/mypage/(网页登录后的首页url)
playwright codegen --load-storage=auth.json https://www.bizreach.jp/mypage/(网页登录后的首页url)
(5)playwright录制器自动生成元素定位语句
(6)page.pause()断点
在代码中加入page.pause()进入断点状态,可以在页面上直接调试代码
(7)网页最大化
方法一:args =['--start-maximized']
不过试了一下在mac系统没有生效
from playwright.sync_api import sync_playwright
doubanMovieURL = "https://movie.douban.com/"
with sync_playwright() as p:
browser = playwright.chromium.launch(
headless=False,
args=['--start-maximized']
)
context = browser.new_context(no_viewport=True)
page = context.new_page()
page.goto(doubanMovieURL)
print(page.title())
page.pause()
context.close()
browser.close()
方法二 直接设置分辨率
from playwright.sync_api import sync_playwright
doubanMovieURL = "https://movie.douban.com/"
with sync_playwright() as p:
browser = p.chromium.launch(headless=False)
context = browser.new_context(viewport={"width": 1920, "height": 1080}) # 设置 viewport 为屏幕分辨率
page = context.new_page()
page.goto(doubanMovieURL)
print(page.title())
page.pause()
context.close()
browser.close()
(8)启动chrome,edge浏览器(无痕浏览器)
playwright install --help 可以查看playwright支持的浏览器
在browser = p.chromium.launch(headless=False)中指定,channel=“chrome”
指定channel=“msedge”,将打开edge浏览器
指定打开safari浏览器:
browser = p.webkit.launch(headless=False)
from time import sleep
from playwright.sync_api import sync_playwright
import os
doubanMovieURL = "https://movie.douban.com/"
USER_DIR_PATH = os.path.expanduser("~/Library/Caches/Safari/User_Data")
with sync_playwright() as p:
context = p.webkit.launch_persistent_context(
user_data_dir=USER_DIR_PATH,
headless=False
)
page = context.new_page()
page.goto(doubanMovieURL)
print(page.title())
sleep(1)
context.close()
(9)启动带缓存的本地浏览器
启动带本地缓存的浏览器可,绕过登录时的一些验证。
windows系统启动带缓存的chrome浏览器
from time import sleep
from playwright.sync_api import sync_playwright
import getpass
doubanMovieURL = "https://movie.douban.com/"
USER_DIR_PATH = fr"C:\Users\{getpass.getuser()}\AppData\Local\Google\Chrome\User Data"
with sync_playwright() as p:
context = p.chromium.launch_persistent_context(
user_data_dir=USER_DIR_PATH,
headless=False,
channel="chrome"
)
page = context.new_page()
page.goto(doubanMovieURL)
print(page.title())
sleep(1)
context.close()
在macOS浏览器启动带缓存的webkit浏览器
根据chatgpt的回答,目前好像还无法支持启动带缓存的Safari浏览器
from time import sleep
from playwright.sync_api import sync_playwright
import os
doubanMovieURL = "https://movie.douban.com/"
with sync_playwright() as p:
context = p.webkit.launch_persistent_context(
user_data_dir=os.path.expanduser("~/Library/Caches/Safari/User_Data"),
headless=False
)
page = context.new_page()
page.goto(doubanMovieURL)
print(page.title())
sleep(1)
context.close()
(10)录制视频
视频在浏览器上下文关闭时保存。如果您手动创建浏览器上下文,请确保browser_context.close(),会在调用close的时候保存视频。
from playwright.sync_api import sync_playwright
with sync_playwright() as p:
#slow_mo=1000 每个操作有1s的停顿
browser = p.chromium.launch(headless=False, slow_mo=1000)
#record_video_dir="videos/"指定视频存放路径
context = browser.new_context(record_video_dir="videos/")
page = context.new_page()
page.goto("https://www.bizreach.jp/")
page.get_by_role("link", name="ログイン", exact=True).click()
page.get_by_test_id("form-input__email").click()
page.get_by_test_id("form-input__email").fill("123@gmail.com")
page.get_by_test_id("form-input__password").click()
page.get_by_test_id("form-input__password").fill("password123")
page.get_by_test_id("form__submit-button").click()
#context.close()时保存视频
context.close()
browser.close()
执行后视频自动保存
视频默认800*800,也可以指定视频大小
context = browser.new_context(
record_video_dir = "videos/",
record_video_size={"width": 640, "height": 480}
)
(11)Trace Viewer测试追踪功能
Playwright Trace Viewer可以探索记录playwright测试跟踪。使用browser_context.tracing API记录追踪
browser = chromium.lanch()
context = browser.new_context()
#Start tracing before creating/ navigating page.
context.tracing.start(screenshots=True,snapshots=True,sources =True)
page = context.new_page()
page.goto("https//playwright.dev")
#Stop tracing and export it into a zip archive.
context.tracing.stop(path = "trace.zip")
这将记录跟踪并将其放入名为trace.zip
可以使用playwright CLI活在您的浏览器中打开保存的trace.playwright.dev
playwright show-trace trace.zip
from playwright.sync_api import sync_playwright
# 复制 Chrome 用户数据到新目录
with sync_playwright() as p:
browser = p.chromium.launch(
headless=False,
slow_mo=1000,
channel="chrome"
)
context = browser.new_context()
# 开始追踪 trace.start
context.tracing.start(screenshots=True, snapshots=True, sources=True)
page = context.new_page() # 创建新页面
page.goto("https://www.douban.com/")
page.frame_locator("#anony-reg-new iframe").get_by_text("密码登录").click()
page.frame_locator("#anony-reg-new iframe").get_by_placeholder("手机号 / 邮箱").click()
page.frame_locator("#anony-reg-new iframe").get_by_placeholder("手机号 / 邮箱").fill("123@123.com")
page.frame_locator("#anony-reg-new iframe").get_by_placeholder("手机号 / 邮箱").press("Tab")
page.frame_locator("#anony-reg-new iframe").get_by_placeholder("密码").fill("password")
page.frame_locator("#anony-reg-new iframe").get_by_text("登录豆瓣").click()
print(page.title())
# 追踪结束
context.tracing.stop(path="trace.zip")
page.close() # 关闭页面
context.close()
browser.close()
查看trace:
方法一:在terminal中,进入trace.zip的文件夹,然后执行:playwright show-trace trace.zip
方法二,访问https://trace.playwright.dev/ 选中trace.zip查看
选中call,可以查看每一步的详细参数
(12)保存cookie,解决反复登录问题
方法一: storageState保存登录cookies
playwright提供了一种在测试中重用登录状态的方法。这样可以只登录一次,然后跳过所有测试的登录步骤。
playwright提供browserContext.storageState(options)方法,可用于从景观身份验证的上下文中检索存储状态,然后创建具有与填充状态的新上下文。
cookie和本地存储状态可以跨不同的浏览器使用。取决于应用程序的身份验证模型:某些应用程序可能需要cookie和本地存储。
...登录操作代码
#保存storage state 到指定文件
storage = context.storage_state(path="auth/state.json")
#-----------------------------
context.close()
browser.close()
执行后会在本地保存一个state.json文件
这样在其他地方就可以使用本地的cookies,实现免登录
#create a new context with the saved storage state
context = browser.new_context(storage_state ="state.json")
登录豆瓣(!!!登录之后一定要预留登录跳转时间,有些登录时还有其他滑动验证等等,不然取不到cookie信息)
from time import sleep
from playwright.sync_api import sync_playwright
# 复制 Chrome 用户数据到新目录
with sync_playwright() as p:
browser = p.chromium.launch(
headless=False,
slow_mo=1000,
channel="chrome"
)
context = browser.new_context()
# 开始追踪 trace.start
# context.tracing.start(screenshots=True, snapshots=True, sources=True)
page = context.new_page() # 创建新页面
page.goto("https://www.douban.com/")
page.frame_locator("#anony-reg-new iframe").get_by_text("密码登录").click()
page.frame_locator("#anony-reg-new iframe").get_by_placeholder("手机号 / 邮箱").click()
page.frame_locator("#anony-reg-new iframe").get_by_placeholder("手机号 / 邮箱").fill("123@123.com")
page.frame_locator("#anony-reg-new iframe").get_by_placeholder("手机号 / 邮箱").press("Tab")
page.frame_locator("#anony-reg-new iframe").get_by_placeholder("密码").fill("pswd")
page.frame_locator("#anony-reg-new iframe").get_by_text("登录豆瓣").click()
# 等待登录完成
sleep(20)
# 保存storage state 到指定文件
# 若目录不存在,不会自动创建,需要自己手动创建
storage = context.storage_state(path="auth/douban_state.json")
print(page.title())
# 追踪结束
# context.tracing.stop(path="trace.zip")
page.close() # 关闭页面
context.close()
browser.close()
调用保存下来的douban_state.json文件,直接进入豆瓣小组页面
from playwright.sync_api import sync_playwright
with sync_playwright() as p:
browser = p.chromium.launch(
headless=False,
slow_mo=1000,
channel="chrome"
)
# 读取cookie,实现免登录
context = browser.new_context(
storage_state="auth/douban_state.json"
)
# 开始追踪 trace.start
# context.tracing.start(screenshots=True, snapshots=True, sources=True)
page = context.new_page() # 创建新页面
page.goto("https://www.douban.com/group/")
page.pause()
# 保存storage state 到指定文件
# 若目录不存在,不会自动创建,需要自己手动创建
print(page.title())
# 追踪结束
# context.tracing.stop(path="trace.zip")
page.close() # 关闭页面
context.close()
browser.close()
(13)Mock接口返回,模拟各种异常场景
# mock 处理方法,状态码改成500 模拟服务器异常
def handle(route):
route.fulfill(status=502)
# 拦截请求,模拟返回
page.route("要访问的url", handler=handle)
from time import sleep
from playwright.sync_api import sync_playwright
# 复制 Chrome 用户数据到新目录
with sync_playwright() as p:
browser = p.chromium.launch(
headless=False,
slow_mo=1000,
channel="chrome"
)
context = browser.new_context()
page = context.new_page() # 创建新页面
page.goto("https://www.douban.com/")
page.frame_locator("#anony-reg-new iframe").get_by_text("密码登录").click()
page.frame_locator("#anony-reg-new iframe").get_by_placeholder("手机号 / 邮箱").click()
page.frame_locator("#anony-reg-new iframe").get_by_placeholder("手机号 / 邮箱").fill("1111@qq.com")
page.frame_locator("#anony-reg-new iframe").get_by_placeholder("手机号 / 邮箱").press("Tab")
page.frame_locator("#anony-reg-new iframe").get_by_placeholder("密码").fill("111")
# mock 处理方法,状态码改成500 模拟服务器异常
def handle(route):
route.fulfill(status=502)
# 拦截请求,模拟返回
page.route("https://accounts.douban.com/j/mobile/login/basic", handler=handle)
page.frame_locator("#anony-reg-new iframe").get_by_text("登录豆瓣").click()
sleep(20)
page.pause()
# --------------------
page.close() # 关闭页面
context.close()
browser.close()