playwright启动一个浏览器

一、start() 和stop() 的方式:

from playwright.sync_api import sync_playwright

playwright = sync_playwright().start()
browser = playwright.chromium.launch(headless=False) # 启动 chromium 浏览器
page = browser.new_page() # 打开一个标签页
page.goto("http://xxx.xx.xxx.xx:xx/login") # 打开地址
page.get_by_placeholder("请输入用户名").click() # 点击用户名输入框
page.get_by_placeholder("请输入用户名").fill("test") # 输入用户名
page.get_by_placeholder("请输入密码").click() # 点击密码输入框
page.get_by_placeholder("请输入密码").fill("12345")  # 输入密码
page.get_by_role("button", name="登 录").click() # 点击登录
print(page.title()) # 打印当前页面title
browser.close() # 关闭浏览器对象
playwright.stop()

二、with语句

from playwright.sync_api import sync_playwright

with sync_playwright() as p:
browser = p.chromium.launch(headless=False) # 启动 chromium 浏览器
page = browser.new_page() # 打开一个标签页
page.goto("https://www.baidu.com") # 打开百度地址
print(page.title()) # 打印当前页面title
browser.close() # 关闭浏览器对象
posted on 2023-11-10 14:17  peijiao  阅读(116)  评论(0编辑  收藏  举报