我希望我的脚本在发生错误时重试从上次停止的地方。我正在使用硒下载多个报告。有时,报告将无法正确加载。我希望脚本在出错时能记住它在哪里,然后重试以提取报告。 (我需要脚本来记住x的值)。
这是一些可能有帮助的代码...(我非常需要帮助)
import time
import os
import glob
from selenium.webdriver.common.action_chains import ActionChains
from selenium.common.exceptions import MoveTargetOutOfBoundsException
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.common.exceptions import NoSuchElementException
from selenium.common.exceptions import NoAlertPresentException
for x in range(1, 51):
while True:
try:
fp = webdriver.FirefoxProfile('C:/Users//Documents/FirefoxProfile')
browser = webdriver.Firefox(fp)
browser.get('https://reportlocation/')
time.sleep(8)
browser.find_element_by_id("ctl00_PlaceHolderMain_login_UserName").clear()
browser.find_element_by_id("ctl00_PlaceHolderMain_login_UserName").send_keys("ytb971")
browser.find_element_by_id("ctl00_PlaceHolderMain_login_password").clear()
browser.find_element_by_id("ctl00_PlaceHolderMain_login_password").send_keys("Fender25")
browser.find_element_by_id("ctl00_PlaceHolderMain_login_login").click()
#gets user to reporting front end
ReportMgr= browser.find_element_by_partial_link_text('Report Manager')
ReportMgr.click()
time.sleep(5)
CustomReport= browser.find_element_by_partial_link_text('Custom Report')
CustomReport.click()
time.sleep(5)
ProgramManagement= browser.find_element_by_partial_link_text('Program Management')
ProgramManagement.click()
ProgramManagement= browser.find_element_by_partial_link_text('Program Management').send_keys(Keys.ARROW_LEFT)
#pulls reports
browser.find_element_by_partial_link_text('Program Management').click()
time.sleep(10)
browser.find_element_by_partial_link_text('Program Management').send_keys(Keys.ARROW_DOWN * x, Keys.ENTER, Keys.ENTER)
time.sleep(30)
browser.find_element_by_css_selector("#ctl00_PlaceHolderMain_ReportViewer1_HtmlOutputReportResults2_CSVButton_ImageAnchor > img").click()
time.sleep(10)
browser.find_element_by_partial_link_text('Program Management').click()
time.sleep(10)
browser.quit()
except:
continue
else:
break
最佳答案
您在此处执行的操作是遍历50个值的x
,一旦一次访问失败,您便会递归地再次遍历所有50个值。重复逻辑应该看起来像这样:
for x in range(1, 51):
while True: # or some condition to put a bound on retries
try:
...
except:
continue
else:
break
therest()
这样,您就可以在循环中的50个值上捕获每个异常,并在运行的迭代中执行重试,因此记住
x
的当前值就不会产生问题。注意在else
语句中使用了try
:如果没有发生异常,则执行else
子句;这是您要停止使用x
的当前值重试的时候。关于python - 重试python中脚本/程序在哪里记住变量值,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/35879625/