使用selenium,我正在从网页下载一些文件。周一我需要下载周五、周六和周日的信息。每隔一天我只需要昨天。我写了一个if/else语句来实现这一点,并将代码复制粘贴到else语句中。一定有一种更像蟒蛇的方式来写这篇文章,但我还是个新手。
today = datetime.date.today()
yesterday = str(today - timedelta(days=1))
if today.weekday() == 0:
fri = str(today - timedelta(days=3))
sat = str(today - timedelta(days=2))
weekend = [fri, sat, yesterday]
for day in weekend:
# Needs to go first otherwise page won't load
date_field = driver.find_element_by_xpath(
"""//*[@id="id blah blah"]""")
date_field.send_keys(day)
org_list = driver.find_element_by_xpath(
"""//*[@id="id blah blah"]/option[text()="string"]""").click()
delay = 5
try:
table_chk = WebDriverWait(driver, delay).until(
EC.presence_of_element_located((By.XPATH, """//*[@id="id blah blah"]""")))
export_btn = driver.find_element_by_xpath(
"""//*[@id="id blah blah"]""")
export_btn.click()
date_field = driver.find_element_by_xpath(
"""//*[@id="id blah blah"]""")
date_field.clear()
org_list = driver.find_element_by_xpath(
"""//*[@id="id blah blah"]/option[1]""").click()
except TimeoutException:
print("Loading took too much time!")
time.sleep(2)
else:
# Needs to go first otherwise it doesn't work
date_field = driver.find_element_by_xpath(
"""//*[@id="id blah blah"]""")
date_field.send_keys(yesterday)
org_list = driver.find_element_by_xpath(
"""//*[@id="id blah blah"]/option[text()="string"]""").click()
delay = 5
try:
table_chk = WebDriverWait(driver, delay).until(
EC.presence_of_element_located((By.XPATH, """//*[@id="id blah blah"]""")))
export_btn = driver.find_element_by_xpath(
"""//*[@id="id blah blah"]""")
export_btn.click()
except TimeoutException:
print("Loading took too much time!")
如何有效地重复代码,但在星期一的星期五、星期六、星期日运行多次,前一天只运行一次,一周中每隔一天运行一次?
使其始终循环,但通过编程将集合定义为在大多数情况下作为单个元素循环,并在需要时循环多天:
today = datetime.date.today()
# No need to define yesterday; we'll make it as needed next
if today.weekday() == 0:
# Today is Monday, quickly get the days for Friday-Sunday
days = [today - timedelta(days=i) for i in (3, 2, 1)]
else:
# Today is not Monday, just check yesterday
days = [today - timedelta(days=1)]
# days is now either one element list of just yesterday, or the whole weekend
# loop runs once or three times, as needed, with the same code
for day in days:
# Complete body of original for day in weekend: loop goes here
如果你真的想把代码重复降到最低,你可以把循环前的代码减少到:
today = datetime.date.today()
num_days_to_check = 3 if today.weekday() == 0 else 1
days = [today - timedelta(days=i) for i in range(num_days_to_check, 0, -1)]
因为实际上,所有不同的是你需要检查之前的天数,1或3,所以条件可以简化为在两者之间选择一行,其余的只是基于最初的决策点。