将 playwright 连接到已经打开的浏览器和页面,直接调试核心代码,提高调试效率
调试时省掉整个测试流程里,登录,输入密码的阶段
可以小改动快速调试,调试时间小于 1s
同时也适用于有框架包装的实际项目
windows
python
playwright
主要涉及以下几个关键部分:
cd C:\Program Files\Google\Chrome\Application && chrome.exe --remote-debugging-port=9222 --user-data-dir="C:\playwright\user_data"
--remote-debugging-port 指定浏览器调试端口号
这里可以随机指定一个端口号,不要指定为已经被占用的端口号
--user-data-dir 用户配置文件目录
这里需要单独指定一个文件夹目录(不存在会新建),如果不显式指定该参数,运行会污染浏览器默认的配置文件
如下:
验证 debug 模式是否打开成功:http://localhost:9222/json/version
class Debug():
def __init__(self):
# Start a new session with Playwright using the sync_playwright function.
with sync_playwright() as playwright:
# Connect to an existing instance of Chrome using the connect_over_cdp method.
browser = playwright.chromium.connect_over_cdp("http://localhost:9222")
# Retrieve the first context of the browser.
default_context = browser.contexts[0]
# Retrieve the first page in the context.
page = default_context.pages[0]
# Print the title of the page.
print(f'You are now at: {page.title()}')
print(f'You are now at: {page.url}')
self.myUIClass= YourUIClass(page)
########### here to debug your code ###########
self.myUIClass.goto_home()
if __name__ == "__main__":
Debug()
https://playwright.dev/python/docs/api/class-browsertype#browser-type-connect-over-cdp
https://stackoverflow.com/questions/71362982/is-there-a-way-to-connect-to-my-existing-browser-session-using-playwright
https://blog.csdn.net/lilongsy/article/details/130560129