Home > Software design >  Python Selenium - list index out of range
Python Selenium - list index out of range

Time:05-04

I'm trying Selenium for the very first time. I'm facing a strange problem trying to access a list of elements.

I have an HTML table (1 row, 7 cols) and I want to access an exact column of an exact row. This is the WORKING code:

table_id = driver.find_element(By.CLASS_NAME, "table_class")
rows = table_id.find_elements(By.TAG_NAME, "tr")
for row in rows:     # not necessary, I only have 1 row
    cols = row.find_elements(By.TAG_NAME, "td")
    for col in cols: # not necessary, I only need to access the 5th elem
        print(col.text)

The problem is that if I try to use the indexes it doesn't works

cols = rows[0].find_elements(By.TAG_NAME, "td")
for col in cols:
 print(col.text)

Or if I try to access only the 5th column using cols[4] I always get list index out of range. I can't understand why it works using the for loop but I cannot access using indexes. Thanks

CodePudding user response:

Make sure you only have one row. Maybe because you use a for loop, It gets through a row that is empty of the elements you are looking for, therefore returning an empty list and showing you the error.

Another solution would be, try to access the elements by XPATH.

rows = table_id.find_elements_by_xpath("""""")

And do the same for cols variable as well.

CodePudding user response:

I think you are trying to access the row variable, that was defined only for iterating the loop. Shouldn't it be cols = rows[0].find_elements(By.TAG_NAME, "td")?

  • Related