python - 如何刷新页面直到正确加载(由于错误 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)
解决方案
当这种情况发生时,您至少应该在断言中发布警告。这样你就知道发生了什么错误。如果您这样做,以下内容将帮助您...
在页面初始化或开始加载相关页面时添加此内容。您也可以在任何页面上执行此操作,真的。
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()
推荐阅读
- delphi - 如何生成一个名称与项目名称不同的二进制文件?
- python-3.x - 从python中的列表生成一个枚举类
- python - 将 rasa 部署到 App 引擎时出现 Google 云构建权限错误
- javascript - 如何在数据库中保存注册发布请求
- python - 根据另一个数据帧的匹配行和列填充数据帧中的值
- reactjs - 将 useEffect 与 React-redux 一起使用
- python - 如何将自定义数据集实现到 pytorch 项目
- gremlin - Gremlin Javascript 遍历永远不会解决
- java - Gradle 下载源失败
- python - 使用 Numpy 而不在数组中获得额外的维度