playwright_run_path.py 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. import asyncio
  2. from playwright.async_api import async_playwright, Playwright
  3. from pathlib import Path
  4. from playwright.async_api import Playwright, Error as PlaywrightError
  5. async def run(playwright: Playwright):
  6. chromium = playwright.chromium # or "firefox" or "webkit".
  7. chrome_exe = Path(r"C:\Program Files\Google\Chrome\Application\chrome.exe")
  8. print(f"chrome_exe.exists() {chrome_exe.exists()}")
  9. browser = await chromium.launch(
  10. executable_path=chrome_exe,
  11. headless=False
  12. )
  13. print(f"executable_path: {chromium.executable_path}")
  14. page = await browser.new_page()
  15. await page.goto("http://example.com")
  16. body = await page.inner_html("body")
  17. print(body)
  18. # other actions...
  19. # await browser.close()
  20. async def connect(playwright: Playwright, port=9321, host='localhost'):
  21. retry = 0
  22. while retry < 5:
  23. try:
  24. browser = await playwright.chromium.connect_over_cdp(f"http://{host}:{port}")
  25. # 捕获这个失败 playwright._impl._errors.Error: BrowserType.connect_over_cdp: connect ECONNREFUSED ::1:932
  26. except PlaywrightError as e:
  27. # 捕获 Playwright 的异常
  28. print(f"Caught a Playwright error: {e}")
  29. print("connect_over_cdp error")
  30. asyncio.sleep(0.5)
  31. retry += 1
  32. return
  33. context = await browser.new_context()
  34. page = await context.new_page()
  35. await page.goto("https://cn.bing.com/")
  36. print(await page.title())
  37. print(await page.inner_html())
  38. async def main():
  39. async with async_playwright() as playwright:
  40. await connect(playwright)
  41. asyncio.run(main())