| 12345678910111213141516171819202122232425262728293031323334353637383940414243 |
- import asyncio
- from playwright.async_api import async_playwright, Playwright
- from pathlib import Path
- from playwright.async_api import Playwright, Error as PlaywrightError
- async def run(playwright: Playwright):
- chromium = playwright.chromium # or "firefox" or "webkit".
- chrome_exe = Path(r"C:\Program Files\Google\Chrome\Application\chrome.exe")
- print(f"chrome_exe.exists() {chrome_exe.exists()}")
- browser = await chromium.launch(
- executable_path=chrome_exe,
- headless=False
- )
- print(f"executable_path: {chromium.executable_path}")
- page = await browser.new_page()
- await page.goto("http://example.com")
- body = await page.inner_html("body")
- print(body)
- # other actions...
- # await browser.close()
- async def connect(playwright: Playwright, port=9321, host='localhost'):
- retry = 0
- while retry < 5:
- try:
- browser = await playwright.chromium.connect_over_cdp(f"http://{host}:{port}")
- # 捕获这个失败 playwright._impl._errors.Error: BrowserType.connect_over_cdp: connect ECONNREFUSED ::1:932
- except PlaywrightError as e:
- # 捕获 Playwright 的异常
- print(f"Caught a Playwright error: {e}")
- print("connect_over_cdp error")
- asyncio.sleep(0.5)
- retry += 1
- return
- context = await browser.new_context()
- page = await context.new_page()
- await page.goto("https://cn.bing.com/")
- print(await page.title())
- print(await page.inner_html())
- async def main():
- async with async_playwright() as playwright:
- await connect(playwright)
- asyncio.run(main())
|