首页 > 解决方案 > 如何刷新页面直到正确加载(由于错误 502 等服务器错误)

问题描述

我正在尝试在 python 中使用 selenium web 驱动程序自动化网站。由于服务器错误导致页面未正确加载,因此无法获取可点击元素时卡住。我想创建一个函数,如果它没有正确加载(更具体地说,如果它没有获得可点击元素),它将在 15 秒后自动刷新页面。

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC

driver=webdriver.Chrome(r"C:\Users\Hp\Downloads\chromedriver")

driver.get("https://addguru.in/user/index.php")
driver.maximize_window()

driver.implicitly_wait(15)

username=driver.find_element_by_name("username").send_keys("-------")

password=driver.find_element_by_name("password").send_keys("-------")

driver.implicitly_wait(40)

driver.find_element_by_class_name("submit_btn").click()
""" I want a function here which automatically refresh the page after each 15 sec if  the submit-btn is not clickable (due to propely loading problem) """
browser.find_element_by_id("checkCbtaskdiv").click()


driver.implicitly_wait(10)

标签: pythonseleniumselenium-webdriver

解决方案


当这种情况发生时,您至少应该在断言中发布警告。这样你就知道发生了什么错误。如果您这样做,以下内容将帮助您...

在页面初始化或开始加载相关页面时添加此内容。您也可以在任何页面上执行此操作,真的。

driver.execute_script('''

    window.errorCount = 0;
    window.onerror = function (error, url, line, column, errorMessage) {

        errorCount ++;
        //** Add whatever you like from the error information to this json string.
        errorJson = '{"code":"' + error.Status + '", "error":"' + error.Status + '", "details":"' + errorMessage + '"}';
        //Appending hidden input with details to document. All console errors can be scraped this way, or just ones that stop page load if you like.
        $("body").append("<input type='hidden' class='console-error-saved' id='" + errorCount 
     + '"' value='" + errorJson + "'");

    }
''')

然后,从您的 Selenium 脚本中,在等待预期元素出现时,如果等待超时并且仍然找不到该元素,请运行以下命令:

pageErrors = driver.execute_script('''
    var json = ""; 
    var errors = $('.console-error-saved'); 
    for(var x=0; x < errors.length; x++) { 

        json += $(errors[x]).text(); 
        if(x < errors.length - 1) { 
            json += ","; 
        } 

    } 
    return "[" + json + "]";
''')

现在从 Python 解析 json 以从字符串中获取对象。查找特定错误如 502、503 等并报告,然后调用刷新命令

import json
errors = json.loads(pageErrors)
#... look at the errors and handle them as needed.
# If qualifying error occurred, refresh the page and do your checks again.
driver.refresh()

推荐阅读