Chrome DevTools 获取 websocket 地址

Max*_*lov 5 python selenium google-chrome google-chrome-devtools selenium-webdriver

当使用 Chrome 作为 Selenium Webdriver 时,如下所示:

from selenium import webdriver
driver = webdriver.Chrome(executable_path='chromedriver.exe')
driver.close()
Run Code Online (Sandbox Code Playgroud)

标准输出的第一行始终是这样的:

DevTools listening on ws://127.0.0.1:13007/devtools/browser/53aa377a-3789-4a8a-a565-dfd0f3622d38
Run Code Online (Sandbox Code Playgroud)

我怎样才能在代码中获得这个地址?driver我没有看到任何可能具有此信息的实例的明显方法或属性(仅从名称判断) 。

Jer*_*ome 5

我没有找到如何直接使用网络驱动程序获取它。
但这里有两种选择:

from selenium import webdriver

tmpChromeDir = 'c:\tmp\ChromeTmp'

options = webdriver.ChromeOptions()
options.add_argument('user-data-dir=' + tmpChromeDir)

driver = webdriver.Chrome(chrome_options=options)

with open(tmpChromeDir + '/DevToolsActivePort') as fp:
    port = fp.readline().replace("\n", "")
    path = fp.readline().replace("\n", "")

print('---> ws://127.0.0.1:' + port + path)
Run Code Online (Sandbox Code Playgroud)

或者

from selenium import webdriver
import requests

options = webdriver.ChromeOptions()
options.add_argument('remote-debugging-port=9222')

driver = webdriver.Chrome(chrome_options=options)

result = requests.get('http://127.0.0.1:9222/json/version').json()

print(result['webSocketDebuggerUrl'])
Run Code Online (Sandbox Code Playgroud)

  • 对于第二个选项:如果您不知道远程调试端口(或者您不想/不能将其硬编码在源代码中),那么您可以从 webdriver 获取主机和端口: `webdriver.capability['goog :chromeOptions']['调试器地址']` (2认同)

Aph*_*hid 0

主人driver.command_executor._conn.host

其余的:如果可以实现这一点,我很确定您将需要使用网络驱动程序执行 javascript。我找不到任何明显的方法来收集这一点,但我很好奇为什么这在运行时对您有用?