首页 > 解决方案 > 我的尝试有什么问题,除了?我没有得到任何打印,也没有错误

问题描述

python和自动化非常新。我们的网站在页面顶部有一个计数器,用于倒计时到星期五的日子。它包含数字,然后是文本 - 直到 #friday 的天数(除了 friday,它没有数字,并显示 It's #friday!)

我星期五的代码正在运行。

elif datetime.datetime.today().weekday() == 4:
countdown_text = driver.find_element_by_class_name("friday-text").text
try:
    if countdown_text == "IT'S #FRIDAY":
        print("Friday Counter is correct. It's Friday.")
except:
    print("Friday Counter is incorrect")

我的问题似乎是将数字和文本联系在一起。这就是我所拥有的。

if datetime.datetime.today().weekday() == 0:
countdown_text = driver.find_element_by_class_name("friday-text").text
countdown_number  = driver.find_element_by_class_name("count")
try:
    if countdown_text == "DAYS UNTIL #FRIDAY" and countdown_number == 4:
        print("Friday Counter is correct. It's Monday - unfortunately.")
except:
    print("Friday Counter is incorrect.")

我目前没有输出,今天也没有错误。

标签: pythonautomationwebdriverselenium-chromedriver

解决方案


你在上面看到的是一份if, else工作。 try/except非常非常好,但是我没用过。我选择不使用 try/except,因为我认为它是复杂性的“下一个级别”。

from datetime import datetime
import sys
def tell_time():
    print(datetime.now())
    
try:
    tell_time()
except Exception as e:
    print(
        "Error on line {}".format(sys.exc_info()[-1].tb_lineno),
        type(e).__name__,
        e,
    )

在这里的例子:

  1. 我们将工作拆分为小功能
  2. 我们使用try尝试运行代码,除非函数没有正确退出。tell_time()
  3. 如果尝试运行代码失败,您可以尝试运行另一个函数,并记录到文件,或者什么都不做(这是您的代码您的想象力)。
  4. 尝试在函数中添加一些错误代码tell_time(),尝试中断tell_time()并运行代码,看看它如何返回异常中的内容?
  5. 您可以为每次失败编写异常,甚至可以将异常用作 if/else,但这需要更多的输入,并且在您看到代码正常工作之前需要做更多的事情(距星期五还有 3 天!)。

推荐阅读