下面的代码给出错误,因为未定义“星期五”。如果缺少任何内容,请帮我。另外,如果我将'friday'和'prev_day'变量的位置与其他位置交换,则会收到未定义'prev_day'的错误消息。
import unittest
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
import datetime
d = datetime.date.today()
if d.weekday() == 0:
tdelta = datetime.timedelta(days=3)
friday = d - tdelta
elif d.weekday() in range(1,5):
tdelta1 = datetime.timedelta(days=1)
prev_day = d - tdelta1
class ClassName(unittest.TestCase):
def setUp(self):
self.driver = webdriver.Chrome(executable_path="C:\\Users\sameerj\IdeaProjects\chromedriver.exe")
def test_as_on_date(self):
driver = self.driver
driver.maximize_window()
driver.get("website")
login = driver.find_element_by_id("Email")
login.send_keys("email")
password = driver.find_element_by_id("Password")
password.send_keys("password")
password.send_keys(Keys.ENTER)
driver.find_element_by_id("menu_name").click()
driver.find_element_by_partial_link_text("page name").click()
date = driver.find_element_by_id("lblAsOn").text
new = datetime.datetime.strptime(date,'%m/%d/%Y')
data_date = new.date()
if data_date == friday:
print("Data as on", friday, "for page name")
elif data_date == prev_day:
print("Data as on", prev_day, "for page name")
else:
print("Data update required.")
driver.close()
if __name__ == '__main__':
unittest.main()
答案 0 :(得分:2)
这是常见的错误类型
让我来分解你的错误
if d.weekday() == 0:
tdelta = datetime.timedelta(days=3)
friday = d - tdelta
elif d.weekday() in range(1,5):
tdelta1 = datetime.timedelta(days=1)
prev_day = d - tdelta1
如果我们执行您的程序
如果d.weekday() == 0
持有假
然后它将转到
elif d.weekday() in range(1,5):
但您的friday = d - tdelta
处于if
状态。这就是为什么它显示错误
解决方案,您必须在friday
条件之外定义if
,并在if
条件中重新分配值
您可以这样解决
friday = None
prev_day = None
d = datetime.date.today()
if d.weekday() == 0:
tdelta = datetime.timedelta(days=3)
friday = d - tdelta
elif d.weekday() in range(1,5):
tdelta1 = datetime.timedelta(days=1)
prev_day = d - tdelta1
答案 1 :(得分:0)
new = datetime.datetime.strptime(date,'%m/%d/%Y')
data_date = new.strftime("%A")
这将为您提供一天的名称(例如:星期五),然后您可以根据自己的情况进行比较,
if data_date == "Friday":
print("Data as on",data_date , "for page name")
对于前几天的比较,您必须这样做
tdelta1 = datetime.timedelta(days=1)
prev_day = (new - tdelta1).strftime("%A")
在做之前,
elif data_date == prev_day:
print("Data as on", prev_day, "for page name")
当使用prev_day替换Friday时,由于python解释器首先找到未定义的变量而出现错误。
答案 2 :(得分:0)
您最好写:
d = datetime.date.today()
if d.weekday() == 0:
tdelta = datetime.timedelta(days=3)
prev_day = None
friday = d - tdelta
elif d.weekday() in range(1, 5):
tdelta1 = datetime.timedelta(days=1)
prev_day = d - tdelta1
friday = None
我对您的建议是使用Python IDE,它们会突出显示此类错误。
我还认为可以使用calendar模块进行检查