rachelvsamuel
rachelvsamuel

Reputation: 1711

selenium: TypeError: 'FirefoxWebElement' object is not subscriptable

I'm getting a TypeError: 'FirefoxWebElement' object is not subscriptable when trying to click on a link in Google:

enter image description here

This is the code that's getting that error:

    button_element = driver.find_element_by_xpath("//span[contains(@class,'cTsG4')]")
    button_element[0].click()

Any idea what's going on?

Upvotes: 0

Views: 4438

Answers (2)

Gaurav Verma
Gaurav Verma

Reputation: 79

There is a slight Typo in the script, it should be:

button_element = find_elements_by_xpath("//span[contains(@class,'cTsG4')]")

as It returns List Of Xpaths so , button_element[0].click() can be used

insted of

find_element_by_xpath("//span[contains(@class,'cTsG4')]")

as It itself return The First Xpath found so, button_element[0].click() will

generate the TypeError as List is subscriptable but Single Element (object) isn't

Upvotes: 0

Lahcen YAMOUN
Lahcen YAMOUN

Reputation: 691

The error is due to the fact that find_element_by_xpath is returning one element and not a list, thus TypeError: 'FirefoxWebElement' object is not subscriptable. But what in the world does subscriptable mean ? well, it basically means that the object implements the __getitem__() method. In other words, it describes objects that are "containers", meaning they contain other objects. This includes lists, tuples, and dictionaries. In your case button_element is unsubscriptable.

So you just need to click the button this way button_element.click() and not button_element[0].click().

If you have many buttons satisfying the XPath that you want to click all of them, you can use find_elements_by_xpath (elements and not element), this will return a list that you can manipulate by iterating over its elements.

Upvotes: 1

Related Questions