我正在尝试使用python中的Selenium Web驱动程序自动化网站。当由于服务器错误导致页面无法正确加载而无法获得clickable元素时,它将卡住。我想创建一个函数,如果未正确加载页面(更具体地说,如果未获得clickable元素),它将在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)
答案 0 :(得分:0)
快速查看一下,根据this answer,您可以将driver.find_element_by_class_name("submit_btn")
的响应(不带.click()
的变量)设置为变量,然后检查该变量是否不是None
while elements is None:
elements = driver.find_element_by_class_name("submit_btn")
for e in elements:
e.click()
答案 1 :(得分:0)
在发生断言时,至少应在声明中发布警告。这样,您就知道发生了什么错误。如果这样做,以下内容将为您提供帮助...
在页面初始化或开始加载有问题的页面时添加此内容。您也可以在任何页面上执行此操作。
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()
答案 2 :(得分:0)
欢迎您。这是方法。
# interval - refresh time
# maxTime - maximum time to wait (rather going into infinite loop)
def refresh_browser_until_element_present(locator_type, locator, interval, maxTime):
startTime = datetime.now()
elements = []
while ((datetime.now() - startTime).seconds<maxTime and len(elements) ==0):
time.sleep(interval)
driver.refresh()
if locator_type == 'xpath':
elements = driver.find_elements_by_xpath(locator)
elif locator_type == 'css':
elements = driver.find_elements_by_css_selector(locator)
如何使用该方法:
refresh_browser_until_element_present('css','#checkCbtaskdiv',15,120)