ClericPy / ichrome

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

incognito模式打开多个tab时无法正常使用 #57

Closed lalalatutu closed 3 years ago

lalalatutu commented 3 years ago

总是会先打开一个无痕窗口后,紧接着打开两个非无痕的窗口,是我使用方式不对吗?希望得到您的答复 运行环境:windows10,python3.8, ichrome =2.8.2,asyncio = 3.4.3

`import asyncio from ichrome.pool import ChromeEngine from inspect import getsource

async def tab_callback(self, tab, url, timeout): await tab.set_url(url, timeout=50) await tab.wait_loading(15) await asyncio.sleep(20) print(await tab.get_cookies()) return await tab.get_cookies()

async def main():

AsyncChromeDaemon.DEFAULT_EXTRA_CONFIG.append("--incognito")

async with ChromeEngine(max_concurrent_tabs=5,
                        clear_after_shutdown=True,
                        # headless=False,
                        headless=True,
                        # disable_image=True,
                        extra_config=["--incognito"],
                        disable_image=False,
                        user_data_dir='./ichrome_user_data',
                        proxy=get_proxy()["http"].split("//")[1]) as ce:
    tasks=[]
    for i in range(2):
        tasks.append(asyncio.ensure_future(ce.do('http://epub.cnipa.gov.cn/', getsource(tab_callback), timeout=50)))

    for task in tasks:
        result = await task
        print(result)
        assert result

# asyncio.run will raise aiohttp issue: https://github.com/aio-libs/aiohttp/issues/4324
# asyncio.get_event_loop().run_until_complete(main())

if name == "main": asyncio.get_event_loop().run_until_complete(main())`

ClericPy commented 3 years ago

白天上班没法回复

我看了下貌似因为无痕模式启动的时候用 Chrome CDP 操作是无法连上进行操作的

"C:/Program Files (x86)/Google/Chrome/Application/chrome.exe" --remote-debugging-address=127.0.0.1 --remote-debugging-port=9222 --user-data-dir=C:\Users\ld\ichrome_user_data\chrome_9222 --incognito about:blank

以上是启动命令

http://127.0.0.1:9222/json/new 这个是新开 tab 的命令

简单地说, 当前 ichrome 版本里无痕模式新建 tab 的方式用的 HTTP 是不支持的, 只能连到已有的 tab 上面进行操作. 之后我看看要不要换掉新建 tab 的实现方式(使用 Target 的 ws 方式). 所以如果你确定需要无痕模式, 使用单独的 AsyncChromeDaemon 来自行操作吧, ChromeEngine 这个类是拿来做批处理使用的, 不是太灵活.

PS: 发多行代码在 md 上是使用 3 个反引号的. 然后无痕模式很有必要么? 网上搜了下挺多人推荐的就是单独开一个 user data dir 就隔离了环境, 或者我更推荐在 tab 里面使用 tab.clear_cookies 以及 js 清理 localstorage 什么的

ClericPy commented 3 years ago

试了下, 就算用 Target.createTarget 也没办法在那个无痕模式创建标签页... 估计 /json/new 底层也用的那接口. 所以还是考虑不要使用 ChromeEngine 而是自己调度吧, 用 Target.createBrowserContext 的方式做到类似隐私的方式 (Creates a new empty BrowserContext. Similar to an incognito profile but you can have more than one.)

https://chromedevtools.github.io/devtools-protocol/tot/Target/#method-createTarget https://chromedevtools.github.io/devtools-protocol/tot/Target/#method-createBrowserContext