繁体   English   中英

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

[英]Can you please let me know the code to capture the status codes other than 200 in network tab in browser in selenium python?

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

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

selenium 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))

selenium 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 事件

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM