Playwright默认调用的是chromium浏览器,并且使用的是无痕模式。有时我们的一些cookie登录信息保存在我们日常使用的Chrome浏览器上,不想每次运行脚本都要去登录这么麻烦,那么playwright其实也可以直接调用我们平时用的Chrome浏览器去运行。
from playwright.sync_api import Playwright, sync_playwright, expectimport
import subprocess
#输入Chrome浏览器所在路径
chrome_path = r'"C:\Program Files\Google\Chrome\Application\chrome.exe"'
debugging_port = "--remote-debugging-port=9222"
command = f"{chrome_path} {debugging_port}"
subprocess.Popen(command, shell=True)
def run(playwright: Playwright) -> None:
browser = playwright.chromium.connect_over_cdp(("http://localhost:9222"))
context = browser.contexts[0]
page = context.new_page()
其实就是调用了Chrome远程调试功能,运行代码前请关闭现在已经打开的Chrome浏览器,不然Chrome的远程调试功能会无法成功开启导致报错。