84 lines
3.3 KiB
Python
84 lines
3.3 KiB
Python
from playwright.async_api import expect
|
||
from playwright.sync_api import sync_playwright
|
||
|
||
|
||
def playwright_sync_demo():
|
||
# 使用上下文管理器自动管理资源
|
||
with sync_playwright() as p:
|
||
# -------------------- 1. 浏览器配置 --------------------
|
||
# 启动 Chromium 浏览器(设置可视模式方便调试)
|
||
browser = p.chromium.launch(
|
||
headless=False, # 显示浏览器窗口
|
||
slow_mo=1000 # 操作间隔延迟1秒(可视化演示)
|
||
)
|
||
|
||
# -------------------- 2. 上下文与页面初始化 --------------------
|
||
# 创建浏览器上下文(实现隔离的独立环境)
|
||
context = browser.new_context(
|
||
viewport={"width": 1920, "height": 1080}, # 设置视口尺寸
|
||
user_agent="Mozilla/5.0 (Windows NT 10.0; Win64; x64) PlaywrightDemo/1.0" # 自定义UA
|
||
)
|
||
|
||
# 创建新页面
|
||
page = context.new_page()
|
||
|
||
# -------------------- 3. 基础导航操作 --------------------
|
||
page.goto("https://www.baidu.com")
|
||
print("当前页面标题:", page.title())
|
||
|
||
# -------------------- 4. 元素定位与交互 --------------------
|
||
# 定位搜索框并输入文本(自动等待元素可见)
|
||
search_box = page.locator("#kw")
|
||
search_box.fill("Playwright自动化测试")
|
||
|
||
# 定位搜索按钮并点击(自动等待元素可点击)
|
||
search_btn = page.locator("#su")
|
||
search_btn.click()
|
||
|
||
# -------------------- 5. 等待与断言 --------------------
|
||
# 显式等待结果区域加载(最大等待5秒)
|
||
page.wait_for_selector(".result.c-container", timeout=5000)
|
||
|
||
# 使用expect断言搜索结果存在
|
||
# expect(page.locator("text=百度百科")).to_be_visible()
|
||
|
||
# -------------------- 6. 处理弹窗示例 --------------------
|
||
# 注册对话框监听器(自动接受弹窗)
|
||
page.on("dialog", lambda dialog: dialog.accept())
|
||
|
||
# 触发JavaScript弹窗
|
||
page.evaluate("alert('这是一个测试弹窗!');")
|
||
|
||
# -------------------- 7. 执行JavaScript代码 --------------------
|
||
# 修改页面背景色
|
||
page.evaluate("document.body.style.backgroundColor = 'lightblue';")
|
||
|
||
# 获取浏览器环境信息
|
||
user_agent = page.evaluate("navigator.userAgent")
|
||
print("当前UserAgent:", user_agent)
|
||
|
||
# -------------------- 8. 文件上传示例 --------------------
|
||
# 导航到测试页面
|
||
page.goto("https://example.com/upload")
|
||
# 定位文件输入框并上传文件(无需input元素可见)
|
||
file_input = page.locator("input[type=file]")
|
||
file_input.set_input_files("example.txt")
|
||
|
||
# -------------------- 9. 截图与录屏 --------------------
|
||
# 页面截图
|
||
page.screenshot(path="search_result.png", full_page=True)
|
||
|
||
# 开始录屏(仅Chromium支持)
|
||
page.video.start_record()
|
||
# 执行一些操作...
|
||
page.video.stop_record(save_as="recording.webm")
|
||
|
||
# -------------------- 10. 清理资源 --------------------
|
||
# 关闭上下文(自动关闭关联页面)
|
||
context.close()
|
||
# 关闭浏览器
|
||
browser.close()
|
||
|
||
|
||
if __name__ == "__main__":
|
||
playwright_sync_demo() |