import asyncio from playwright.async_api import async_playwright,CDPSession,Page,Locator # 以启动路径的方式启动 chrome def start_chrome(): import subprocess subprocess.Popen( r'"C:\Program Files\Google\Chrome\Application\chrome.exe" --user-data-dir=K:\\code\\upwork\\zhang_crawl_bio\\output\\user_data_dir' ) async def get_win_pos_by_cdp(port=9220, host='localhost'): async with async_playwright() as p: browser = await p.chromium.connect_over_cdp(f"http://{host}:{port}") contexts = browser.contexts if contexts: print(f"contexts {contexts}") context = contexts[0] print(f"context.pages {context.pages}") page = context.pages[1] async def main(): start_chrome() '''一定要在符合浏览器版本的 user_data_dir 下启动 chrome "C:\Program Files\Google\Chrome\Application\chrome.exe" --debug-port=9222 --user-data-dir=K:\\code\\upwork\\zhang_crawl_bio\\output\\user_data_dir2 ''' # await get_win_pos_by_cdp() if __name__ == "__main__": asyncio.run(main())