首页 > 解决方案 > 您能否让我知道在 selenium python 浏览器的网络选项卡中捕获除 200 以外的状态代码的代码吗?

问题描述

我的应用程序有多个页面,我想编写一个代码来捕获浏览器的网络选项卡中除 200 之外的状态。我想使用 Selenium 和 Python 来做到这一点

如果你能分享这个会很有帮助

标签: pythonseleniumnetworkingbrowser

解决方案


硒 4:

from time import sleep
from selenium import webdriver

import json

options = webdriver.ChromeOptions()

options.set_capability("goog:loggingPrefs", {  # old: loggingPrefs
    "performance": "ALL"})

driver = webdriver.Chrome(
    options=options
)

driver.get("https://www.google.com")
sleep(5)

# returns a list of all events
logs = driver.get_log("performance")


#iterate through the list
for log in logs:
    #converting the string to dict
    a= json.loads(log['message'])

    #get the resolved requests and get the response content from it
    if "Network.responseReceived" == a['message']["method"]:
        print(a["message"]["params"]["response"]["url"])
        print(a["message"]["params"]["response"]["status"])

        #you can see the full request object in the demofile2.txt created in your current directory
        f = open("demofile2.txt", "a")
        f.write(json.dumps(a, indent=4, sort_keys=True))

硒 3

from time import sleep
from selenium import webdriver

import json

caps = DesiredCapabilities.CHROME
#as per latest docs
caps['goog:loggingPrefs'] = {'performance': 'ALL'}
driver = webdriver.Chrome(desired_capabilities=caps)

driver.get("https://www.google.com")
sleep(5)

# returns a list of all events
logs = driver.get_log("performance")


#iterate through the list
for log in logs:
    #converting the string to dict
    a= json.loads(log['message'])

    #get the resolved requests and get the response content from it
    if "Network.responseReceived" == a['message']["method"]:
        print(a["message"]["params"]["response"]["url"])
        print(a["message"]["params"]["response"]["status"])

        #you can see the full request object in the demofile2.txt created in your current directory
        f = open("demofile2.txt", "a")
        f.write(json.dumps(a, indent=4, sort_keys=True))

您可以记录 PERFORMANCE 日志,然后获取 Network.receivedresponse 事件


推荐阅读