ClericPy / ichrome

Chrome controller for Humans, based on Chrome Devtools Protocol(CDP) and python3.7+.
https://pypi.org/project/ichrome/
MIT License
227 stars 29 forks source link

能否接管已经打开的浏览器 #108

Closed tmxd09887 closed 1 year ago

tmxd09887 commented 1 year ago

http://127.0.0.1:62329/json/new

{ "description": "", "devtoolsFrontendUrl": "/devtools/inspector.html?ws=127.0.0.1:62329/devtools/page/C672CA19F5D7B9E4DE42128B985C462E", "id": "C672CA19F5D7B9E4DE42128B985C462E", "title": "", "type": "page", "url": "about:blank", "webSocketDebuggerUrl": "ws://127.0.0.1:62329/devtools/page/C672CA19F5D7B9E4DE42128B985C462E" }

通过新建tab返回的json接管这个浏览器?

ClericPy commented 1 year ago
import asyncio

from ichrome import AsyncChrome

async def main():
    data = {
        "description": "",
        "devtoolsFrontendUrl": "/devtools/inspector.html?ws=localhost:9222/devtools/page/4485A0A384D8440C96AB3F17A77BF537",
        "id": "4485A0A384D8440C96AB3F17A77BF537",
        "title": "about:blank",
        "type": "page",
        "url": "about:blank",
        "webSocketDebuggerUrl": "ws://localhost:9222/devtools/page/4485A0A384D8440C96AB3F17A77BF537",
    }
    async with AsyncChrome(host='127.0.0.1', port=9222) as chrome:
        async with chrome.connect_tab(data['id']) as tab:
            await tab.goto("http://bing.com")
            print(await tab.title)

asyncio.run(main())
import asyncio

from ichrome import AsyncTab

async def main():
    data = {
        "description": "",
        "devtoolsFrontendUrl": "/devtools/inspector.html?ws=localhost:9222/devtools/page/4485A0A384D8440C96AB3F17A77BF537",
        "id": "4485A0A384D8440C96AB3F17A77BF537",
        "title": "about:blank",
        "type": "page",
        "url": "about:blank",
        "webSocketDebuggerUrl": "ws://localhost:9222/devtools/page/4485A0A384D8440C96AB3F17A77BF537",
    }
    tab = AsyncTab(flatten=False, **data)
    async with tab():
        await tab.goto("http://bing.com")
        print(await tab.title)

asyncio.run(main())
ClericPy commented 1 year ago

两个方式, 前者用 flatten 模式更优雅一点, 而且新建 tab 也可以把 connect_tab 参数改为 None 就可以了

tmxd09887 commented 1 year ago

感谢,第二种方式成功了