最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

python - Can't use Playwright to control local browser to go pages successfully - Stack Overflow

programmeradmin2浏览0评论

The code I was running:

from playwright.sync_api import Playwright, sync_playwright, expect
from playwright.async_api import async_playwright
import asyncio
import subprocess

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)

async def main() -> None:
    async with async_playwright() as p:
        browser = await p.chromium.connect_over_cdp(("http://localhost:9222"))
        context = await browser.contexts[0]
        page = await context.new_page()
        await page.goto(";)
        print(await page.title())

if __name__ == '__main__':
    asyncio.run(main())

I ran this code, my local Chrome would run and next nothing was happening, could not goto page "; as I expected

Then I got error logs in Command lines.

The error log I got:

PS C:\Code-Repo\Web-Crawler-Playwright> & C:/Users/anaconda3/envs/web-crawler-playwright/python.exe c:/Code-Repo/Web-Crawler-Playwright/tempt_chrome.py
Traceback (most recent call last):
  File "c:/Code-Repo/Web-Crawler-Playwright/tempt_chrome.py", line 22, in <module>
    run(playwright)
  File "c:/Code-Repo/Web-Crawler-Playwright/tempt_chrome.py", line 12, in run
    browser = playwright.chromium.connect_over_cdp(("http://localhost:1234"))
  File "C:\Users\anaconda3\envs\web-crawler-playwright\lib\site-packages\playwright\sync_api\_generated.py", line 14816, in connect_over_cdp
    self._sync(
  File "C:\Users\anaconda3\envs\web-crawler-playwright\lib\site-packages\playwright\_impl\_sync_base.py", line 115, in _sync
    return task.result()
  File "C:\Users\anaconda3\envs\web-crawler-playwright\lib\site-packages\playwright\_impl\_browser_type.py", line 174, in connect_over_cdp
    response = await self._channel.send_return_as_dict("connectOverCDP", params)
  File "C:\Users\anaconda3\envs\web-crawler-playwright\lib\site-packages\playwright\_impl\_connection.py", line 64, in send_return_as_dict
    return await self._connection.wrap_api_call(
  File "C:\Users\anaconda3\envs\web-crawler-playwright\lib\site-packages\playwright\_impl\_connection.py", line 520, in wrap_api_call
    raise rewrite_error(error, f"{parsed_st['apiName']}: {error}") from None
playwright._impl._errors.Error: BrowserType.connect_over_cdp: connect ECONNREFUSED ::1:1234
Call log:
<ws preparing> retrieving websocket url from http://localhost:1234

I tried several methods in order to solve this problem but didn't work at all

  • Replace "http://localhost:9222" with "http://127.0.0.1:9222"
  • Close all my VPN
  • Restart my Chrome process

I want playWright to automatically open my local Chrome and then goto website ";

The code I was running:

from playwright.sync_api import Playwright, sync_playwright, expect
from playwright.async_api import async_playwright
import asyncio
import subprocess

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)

async def main() -> None:
    async with async_playwright() as p:
        browser = await p.chromium.connect_over_cdp(("http://localhost:9222"))
        context = await browser.contexts[0]
        page = await context.new_page()
        await page.goto("https://www.google")
        print(await page.title())

if __name__ == '__main__':
    asyncio.run(main())

I ran this code, my local Chrome would run and next nothing was happening, could not goto page "https://www.google" as I expected

Then I got error logs in Command lines.

The error log I got:

PS C:\Code-Repo\Web-Crawler-Playwright> & C:/Users/anaconda3/envs/web-crawler-playwright/python.exe c:/Code-Repo/Web-Crawler-Playwright/tempt_chrome.py
Traceback (most recent call last):
  File "c:/Code-Repo/Web-Crawler-Playwright/tempt_chrome.py", line 22, in <module>
    run(playwright)
  File "c:/Code-Repo/Web-Crawler-Playwright/tempt_chrome.py", line 12, in run
    browser = playwright.chromium.connect_over_cdp(("http://localhost:1234"))
  File "C:\Users\anaconda3\envs\web-crawler-playwright\lib\site-packages\playwright\sync_api\_generated.py", line 14816, in connect_over_cdp
    self._sync(
  File "C:\Users\anaconda3\envs\web-crawler-playwright\lib\site-packages\playwright\_impl\_sync_base.py", line 115, in _sync
    return task.result()
  File "C:\Users\anaconda3\envs\web-crawler-playwright\lib\site-packages\playwright\_impl\_browser_type.py", line 174, in connect_over_cdp
    response = await self._channel.send_return_as_dict("connectOverCDP", params)
  File "C:\Users\anaconda3\envs\web-crawler-playwright\lib\site-packages\playwright\_impl\_connection.py", line 64, in send_return_as_dict
    return await self._connection.wrap_api_call(
  File "C:\Users\anaconda3\envs\web-crawler-playwright\lib\site-packages\playwright\_impl\_connection.py", line 520, in wrap_api_call
    raise rewrite_error(error, f"{parsed_st['apiName']}: {error}") from None
playwright._impl._errors.Error: BrowserType.connect_over_cdp: connect ECONNREFUSED ::1:1234
Call log:
<ws preparing> retrieving websocket url from http://localhost:1234

I tried several methods in order to solve this problem but didn't work at all

  • Replace "http://localhost:9222" with "http://127.0.0.1:9222"
  • Close all my VPN
  • Restart my Chrome process

I want playWright to automatically open my local Chrome and then goto website "https://www.google"

Share Improve this question asked Mar 30 at 3:52 HorusLiangHorusLiang 512 silver badges7 bronze badges 1
  • 1 Port is different in your error: http://localhost:1234. I can repro your error on linux--problem seems to be the browser just isn't launched yet. Sleeping a few seconds after launching the browser solves the problem for me. – ggorlen Commented Mar 30 at 5:58
Add a comment  | 

1 Answer 1

Reset to default 1

The browser won't necessarily be ready to accept an incoming connection so shortly after launching. Try sleeping a few seconds or polling until the browser is ready:

import asyncio
import subprocess
from playwright.async_api import async_playwright
from time import sleep


chrome_path = r"/snap/bin/chromium"
debugging_port = "--remote-debugging-port=9222"
url = "http://localhost:9222"

command = f"{chrome_path} {debugging_port}"
subprocess.Popen(command, shell=True)


async def main() -> None:
    async with async_playwright() as p:
        for _ in range(100):
            try:
                browser = await p.chromium.connect_over_cdp(url)
                break
            except:
                sleep(1)

        context = await browser.new_context()
        page = await context.new_page()
        await page.goto("https://www.google")
        print(await page.title())


if __name__ == "__main__":
    asyncio.run(main())

But I'm not sure I understand the purpose of this over the standard approach of passing in the executable you want Playwright to launch and letting it handle the connection:

browser = await p.chromium.launch(
    headless=False,
    executable_path=r"/snap/bin/chromium"
)
发布评论

评论列表(0)

  1. 暂无评论