bbfl
bbfl

Reputation: 365

Python Selenium use elif with finding elements

my current code is the following:

    buttons = driver.find_elements(By.XPATH, "...xpath")
    if len(buttons) > 0:
        for idx in range(len(buttons)):
            buttons[idx].send_keys('\n')
            res += 1
        time.sleep(1)
        driver.refresh()
    else:
        nxt = driver.find_element(By.CSS_SELECTOR, ".paging_bootstrap i.fa-angle-right.fa")
        driver.execute_script("arguments[0].click();", nxt)

However I want to change the else with elif and then else so it will look in this order:

    if len(buttons) > 0:
        for idx in range(len(buttons)):
            buttons[idx].send_keys('\n')
            res += 1
        time.sleep(1)
        driver.refresh()
    elif:
        nxt = driver.find_element(By.CSS_SELECTOR, ".paging_bootstrap i.fa-angle-right.fa")
        driver.execute_script("arguments[0].click();", nxt)
    else:
        print("Message")

Any ideas how to do it?

Upvotes: 0

Views: 39

Answers (2)

Jayanth Srivastav
Jayanth Srivastav

Reputation: 81

You are almost correct. You just need to add the condition for elif block like len(buttons) == 0. For example your code can be written as:

if len(buttons) > 0:
        for idx in range(len(buttons)):
            buttons[idx].send_keys('\n')
            res += 1
        time.sleep(1)
        driver.refresh()
elif len(buttons) == 0:
        nxt = driver.find_element(By.CSS_SELECTOR, ".paging_bootstrap i.fa-angle-ight.fa")
        driver.execute_script("arguments[0].click();", nxt)
else:
        print("Message")

Upvotes: 1

MetraDZ
MetraDZ

Reputation: 39

buttons = driver.find_elements(By.XPATH, "...xpath")
    if len(buttons) > 0:
        for idx in range(len(buttons)):
            buttons[idx].send_keys('\n')
            res += 1
        time.sleep(1)
        driver.refresh()
    else:
        try:
            nxt = driver.find_element(By.CSS_SELECTOR, ".paging_bootstrap i.fa-angle-right.fa")
            driver.execute_script("arguments[0].click();", nxt)
        except Exception as e:
            print(e.message)

What do you think about this one?

P.S. Its pretty difficult to figure out, what do you want to achieve with this code, add some more explanation.

Upvotes: 1

Related Questions