Третье исключение не выполняется Python try / except - PullRequest
0 голосов
/ 03 августа 2020

Код моей функции, в основном он запускается по нескольким ссылкам и проверяет различные кнопки, пока не найдет нужную ... попробуйте 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: Сообщение: нет такого element: не удалось найти элемент: {"method": "xpath", "selector": "// button [text () =" Message "]"} (Информация о сеансе: chrome = 84.0.4147.105)

Я думал, что это проблема синтаксиса, но я проверил, как обрабатывать исключения в Интернете, и странно, почему это не работает ..

Ответы [ 2 ]

1 голос
/ 03 августа 2020

Попробуйте вложить try в except. Я предполагаю, что третий вариант, за исключением предыдущего, не работает. Так что попробуйте этот код:

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 
1 голос
/ 03 августа 2020

Что вам нужно, так это вложенный блок 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

Таким образом, он может поймать NoSuchElementException при повторном запуске find_element_by_xpath

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...