Home > Enterprise >  WebElement object is not subscriptable
WebElement object is not subscriptable

Time:03-02

Why is this appening?

This works

time_elements = li_element.find_elements_by_tag_name("time")

message_elements = li_element.find_element(By.TAG_NAME, "span.message")

message_element = message_elements[len(time_elements)-1]

but when I change to:

time_elements = li_element.find_element(By.TAG_NAME, "time")

message_elements = li_element.find_element(By.TAG_NAME, "span.message")

message_element = message_elements[len(time_elements)-1] 
#i need this in order to get the last entry      

it doesn't. I know I'm not giving much but I believe I'm missing something simple.

already tried

time_elements = li_element.find_elements(By.TAG_NAME, "time")

Error:

message_element = message_elements[len(time_elements)-1]
TypeError: 'WebElement' object is not subscriptable

CodePudding user response:

The problem here is that message_elements is not a list.
You are trying to get some object (element) from that list by an index len(time_elements)-1 by

message_elements[len(time_elements)-1]

while message_elements is not a list, it is a single web element object.

CodePudding user response:

See this line

li_element.find_elements_by_tag_name("time")

li_element must be a web element and on top of that, you are using find_elements which will return a list of web elements if found, if not then the size of the list will be zero.

The list name, in this case, is time_elements

When you are writing this line:

message_element = message_elements[len(time_elements)-1]

this means that message_elements is a list and you are looking for the length of time_elements.

Since message_elements in both the cases aren't really a list and it is a single web element, you are facing the exception.

You cannot have an index on a single web element type, it has to be a list of web elements.

  • Related