what to do with IndexError: list index out of range?

hello so im trying to use selenium for clicking on some buttons in the instagram site but while im running the code this message appears and makes the script crash

button2 = driver.find_elements_by_xpath("/html/body/div[3]/div/div/div[3]/button[2]")[0]
IndexError: list index out of range

for another button i set the value of under the bracket to 0 and it worked but now i cant fix other buttons with that solution

button2 = driver.find_elements_by_xpath("/html/body/div[3]/div/div/div[3]/button[2]")[0]
button2.click()
time.sleep(2)

1 answer

  • answered 2019-05-24 18:48 BoarGules

    This line:

    driver.find_elements_by_xpath("/html/body/div[3]/div/div/div[3]/button[2]")
    

    gets back a list. The list can have zero or more entries. When your code indexes into that list, like this

    driver.find_elements_by_xpath("/html/body/div[3]/div/div/div[3]/button[2]")[0]
    

    it is trying to retrieve the first element of the list. But that means that it is assuming that there is at least one element in the list. The error list index out of range is telling you that assumption is false: the list, in this case, is empty.