亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

僅在 Python Selenium 中的 for 循環末尾引發異常

僅在 Python Selenium 中的 for 循環末尾引發異常

開滿天機 2023-09-26 14:53:16
我有這樣的代碼: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 nameID: 3553 - John is correct nameID: 7679 - John is correct nameID: 7677 - Sara is wrong nameID: 3456 - John is correct nameID: 7990 - Michael is wrong nameID: 5654 - John is correct nameID: 1111 - Craig is wrong nameID: 3456 - David is wrong nameID: 9876 - John is correct name循環結束后是否可以檢查輸出列表中是否有人姓名錯誤,并引發異常并僅打印錯誤的 ID 和/或姓名。例如,如果所有姓名都正確或找不到任何人來完成并打印成功消息。
查看完整描述

1 回答

?
牧羊人nacy

TA貢獻1862條經驗 獲得超7個贊

在其自己的列表中跟蹤“錯誤名稱”,然后檢查該列表末尾是否包含某些內容。偽代碼:


errors = []


for element in ...:

    if name_is_wrong:

        errors.append(id_page)


if errors:

    raise YourException("Wrong ids: %s" % ", ".join(errors))

else:

    print("Success")


查看完整回答
反對 回復 2023-09-26
  • 1 回答
  • 0 關注
  • 120 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號