簡體   English   中英

第三個異常未執行 Python 嘗試/除外

[英]Third Exception not executing Python try/except

我的 function 的代碼,基本上它通過多個鏈接運行並檢查各種按鈕,直到找到正確的按鈕.. 嘗試 A,除了 nosuch B 除了 nosuch C ...第三,除了 NoSuchElement。 是我格式錯了還是怎么的?

def followerviewer():

    user_str = " "
    followaction = 0


    for acc_len in range(len(acc_list)):
        user_str = f"{acc_list[acc_len]}"
        driver.get(f"https://instagram.com/{user_str}/")
        try:
            followbutton = driver.find_element_by_xpath('//button[text()="Requested"]')
            followaction = 0
        except NoSuchElementException:

            followbutton = driver.find_element_by_xpath('//button[text()="Message"]')
            followaction = 0

        except NoSuchElementException:
            followbutton = driver.find_element_by_xpath('//button[text()="Follow"]')
            followaction = 1



        if bool(followaction) is True:
            followbutton.click()
        else:
            print("Is already followed")

        time.sleep(0.25)




    return 

我的第三個異常不起作用,我收到此錯誤..

selenium.common.exceptions.NoSuchElementException:消息:沒有這樣的元素:無法定位元素:{"method":"xpath","selector":"//button[text()="Message"]"}(會話信息:鉻=84.0.4147.105)

我認為這是一個語法問題,但我檢查了如何在線處理異常以及它為什么不起作用。

您需要的是嵌套的 try/catch 塊:

    try:
        followbutton = driver.find_element_by_xpath('//button[text()="Requested"]')
        followaction = 0
    except NoSuchElementException:
        try:
            followbutton = driver.find_element_by_xpath('//button[text()="Message"]')
            followaction = 0
        except NoSuchElementException:
            followbutton = driver.find_element_by_xpath('//button[text()="Follow"]')
            followaction = 1

這樣,當您再次運行find_element_by_xpath時,它可以捕獲NoSuchElementException

嘗試在except中嵌套一個try。 我在這里假設第三個除了在前一個失敗的情況下運行。 所以試試這個代碼:

def followerviewer():
 user_str = " "
 followaction = 0


 for acc_len in range(len(acc_list)):
    user_str = f"{acc_list[acc_len]}"
    driver.get(f"https://instagram.com/{user_str}/")
    try:
        followbutton = driver.find_element_by_xpath('//button[text()="Requested"]')
        followaction = 0
    except NoSuchElementException:
       try
           followbutton = driver.find_element_by_xpath('//button[text()="Message"]')
           followaction = 0

       except NoSuchElementException:

           followbutton = driver.find_element_by_xpath('//button[text()="Follow"]')
           followaction = 1



    if bool(followaction) is True:
        followbutton.click()
    else:
        print("Is already followed")

    time.sleep(0.25)




 return 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM