【问题标题】:Raise exception only at the end of for loop in Python Selenium仅在 Python Selenium 中的 for 循环结束时引发异常
【发布时间】:2021-01-16 14:27:03
【问题描述】:

我有这样的代码:

elements = driver.find_elements(By.CSS_SELECTOR, ".names.pages")

for element in elements in range(len(elements)):
    elements[element].click()
    id_page = driver.find_element(By.CSS_SELECTOR, ".id.page")
    try:
        name = driver.find_element(By.CSS_SELECTOR, ".name")
        if name == "John":
            print("ID: " + id_page + " - " + name + " is correct name")
        else:
            print("ID: " + id_page + " - " + name + "is wrong name")
    except:
        print("Can't find the person")
        continue

输出是这样的,但列表要长得多:

ID: 5487 - John is correct name
ID: 3553 - John is correct name
ID: 7679 - John is correct name
ID: 7677 - Sara is wrong name
ID: 3456 - John is correct name
ID: 7990 - Michael is wrong name
ID: 5654 - John is correct name
ID: 1111 - Craig is wrong name
ID: 3456 - David is wrong name
ID: 9876 - John is correct name

是否有可能在循环结束后检查输出列表中是否有姓名错误的人并引发异常并仅打印错误的 ID 和/或姓名。例如,如果所有名称都正确或找不到任何人来完成并打印成功消息。

【问题讨论】:

    标签: python python-3.x selenium for-loop printing


    【解决方案1】:

    在其自己的列表中跟踪“错误名称”,然后检查该列表的末尾是否包含某些内容。伪代码:

    errors = []
    
    for element in ...:
        if name_is_wrong:
            errors.append(id_page)
    
    if errors:
        raise YourException("Wrong ids: %s" % ", ".join(errors))
    else:
        print("Success")
    

    【讨论】:

      猜你喜欢
      • 2017-04-10
      • 1970-01-01
      • 1970-01-01
      • 2020-12-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-11-23
      相关资源
      最近更新 更多