如何使用python selenium获取浏览器网络日志

新手上路,请多包涵

我正在尝试使用 selenium 获取浏览器网络日志来调试请求/响应。你能帮我想办法吗。

我正在使用 selenium 3.14.0 和最新的 Chrome 浏览器。

原文由 Anand S 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 1.5k
1 个回答

使用 python + selenium + firefox

除非必须,否则不要设置代理 - 为了获得出站 API 请求,我使用了此答案中的解决方案,但在 python 中: https ://stackoverflow.com/a/45859018/14244758

 test = driver.execute_script("var performance = window.performance || window.mozPerformance || window.msPerformance || window.webkitPerformance || {}; var network = performance.getEntries() || {}; return network;")

for item in test:
  print(item)

你得到一系列的字典。

这让我可以看到所有的网络请求。我正在使用它从其中一个请求中解析出一个参数,以便我可以使用它来针对 API 发出我自己的请求。

使用 python + selenium + Chrome

编辑:这个答案得到了很多关注,这是我现在使用 Chrome 的方式(取自未检测到的 chromedriver 代码):

 chrome_options = webdriver.ChromeOptions()
chrome_options.set_capability(
                        "goog:loggingPrefs", {"performance": "ALL", "browser": "ALL"}
                    )
driver = webdriver.Chrome(options=chrome_options)

##visit your website, login, etc. then:
log_entries = driver.get_log("performance")

for entry in log_entries:

    try:
        obj_serialized: str = entry.get("message")
        obj = json.loads(obj_serialized)
        message = obj.get("message")
        method = message.get("method")
        if method in ['Network.requestWillBeSentExtraInfo' or 'Network.requestWillBeSent']:
            try:
                for c in message['params']['associatedCookies']:
                    if c['cookie']['name'] == 'authToken':
                        bearer_token = c['cookie']['value']
            except:
                pass
        print(type(message), method)
        print('--------------------------------------')
    except Exception as e:
        raise e from None

使用此方法,您可以解析出浏览器发送到服务器的令牌、api 密钥等。

原文由 grantr 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题