Chrome开发者工具获取WebSocket地址

5
当使用Chrome作为Selenium webdriver时,如下所示:
from selenium import webdriver
driver = webdriver.Chrome(executable_path='chromedriver.exe')
driver.close()

第一行输出到标准输出的内容通常是这样的:

DevTools listening on ws://127.0.0.1:13007/devtools/browser/53aa377a-3789-4a8a-a565-dfd0f3622d38

我该如何在代码中获取这个地址?从名称来看,driver实例似乎没有任何明显的方法或属性可以提供这些信息。

2个回答

5

我没有找到直接使用webdriver获取它的方式。
不过有两个替代方案:

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)

或者

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'])

2
对于第二个选项:如果您不知道远程调试端口(或者您不想/不能在源代码中硬编码它),那么您可以从webdriver获取主机和端口:webdriver.capabilities['goog:chromeOptions']['debuggerAddress'] - eNca

0

主机: driver.command_executor._conn.host

其余内容: 如果可能的话,我相信您需要使用webdriver执行javascript才能实现。我找不到任何明显的方法来获取这个信息,但我很好奇在运行时为什么这对您有用?


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接