Python Selenium使用带查找元素的elif

问题描述

我当前的代码如下:

    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)

但是我想用elif改变else,然后再改变else,以便它按此顺序显示

    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,nxt)
    else:
        print("Message")

有什么想法怎么做?

解决方法

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)

您对此有何看法?

P.S。很难弄清楚,您想用此代码实现什么,并添加更多说明。

,

您几乎是正确的。您只需要为elif块添加条件,例如len(buttons)== 0。 例如,您的代码可以写为:

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")