可查看白月黑羽,很详细
Playwright web自动化 - Python版_哔哩哔哩_bilibili
1、安装使用
# 1、安装playwright
pip install playwright
pip install playwright -i https://pypi.douban.com/simple
# 2、安装chromium浏览器
playwright install #安装3个浏览器
playwright install chromium
# 3、引入模块
From playwright.sync_api import sync_playwright
# 4、封装启动方法
class BrowserLauncher
def __init__(self);
self.playwright = None
self.browser = None
self.page = None
def laucher_chrome(self, headless=FALSE, channel="chrome"):
try:
self.playwright = sync_playwright().start()
self.browser =self.playwright.chromium.launch(headless=headless,
channel=channel)
self.page = self.browser.new_page()
return self.page
except Exception as e:
print(f"浏览器启动失败: {str(e)}")
self.close()
raise
def close(self):
#检查 self.browser是否存在(非None),避免在未初始化浏览器时调导致 AttributeError
if self.browser:
self.browser.close()
if self.playwright:
self.playwright.stop()
2、实例
from playwright.sync_api import sync_playwright
class BrowserManager:
def __init__(self):
self.playwright=None
self.browser=None
self.page=None
def launchChrome(self,headless=False, channel="chrome"):
"""
launchChrome为无头模式下启动谷歌浏览器
:param headless:
:param channel:
:return:
"""
self.playwright = sync_playwright().start()
self.browser = self.playwright.chromium.launch(headless=headless, channel=channel)
self.page = self.browser.new_page()
return self.page
def close(self):
"""
关闭浏览器、关闭playwright
"""
self.browser.close()
self.playwright.stop()
if __name__ == "__main__":
# 使用示例
BrowserManager = BrowserManager()
try:
page =BrowserManager.launchChrome()
# 访问网页并执行操作
page.goto("https://www.baidu.com/")
print("当前标题:", page.title())
page.wait_for_timeout(2000) # 等待2秒查看效果
finally:
BrowserManager.close()
3、expect常用的断言方法
断言 描述
expect(page).to_have_title() 页面有标题
expect(page).to_have_url() 页面有URL
expect(locator).to_be_checked() 断言是否被选中
expect(locator).to_be_disabled() 元素是禁用状态
expect(locator).to_be_editable() 元素是可编辑状态
expect(locator).to_be_enabled() 元素是可用的
expect(locator).to_be_focused() 元素已获取焦点
expect(locator).to_be_hidden() 元素是不可见的
expect(locator).to_be_visible() 元素可见
expect(locator).to_contain_text() 元素包含文本
expect(locator).to_have_attribute() 元素具有一个 DOM 属性
expect(locator).to_have_class() 元素具有class属性
expect(locator).to_have_count() 列表具有确切数量的子元素
expect(locator).to_have_css() 元素具有 CSS 属性
expect(locator).to_have_id() 元素有ID
expect(locator).to_have_js_property() 元素有JS属性
expect(locator).to_have_text() 元素与文本匹配
expect(locator).to_have_value() 输入框具有一个值
expect(locator).to_have_values() 选择框有选中的选项
expect(response).to_be_ok() 响应状态正常