how do I get around this error 'webelement does not support indexing"[webdriver][python]

10,819

Solution 1

Like most of the Selenium WebDriver bindings, if you only specify "element", you will only return the first found element. However, if you specify "elements" in your method, it will return an array of elements found.

So your code should be:

page = driver.find_elements_by_xpath('//td[@class="mceIframeContainer mceFirst mceLast"]')[1]

See http://selenium.googlecode.com/svn/trunk/docs/api/py/webdriver_remote/selenium.webdriver.remote.webdriver.html?highlight=find_element_by_xpath#selenium.webdriver.remote.webdriver.WebDriver.find_elements_by_xpath

Solution 2

the [1] needs to be added in part of the string

for example for a bunch of identical forms on a webpage, the first xpath might be

/html/body/form/table/tbody/tr[1]/td[2]/input

and the second would be

/html/body/form/table/tbody/tr[2]/td[2]/input

OR you might be able to use find_elements_by_xpath instead, and then they could be indexable thats find_element***s***_by_xpath with an S

Share:
10,819
gallly
Author by

gallly

;

Updated on June 10, 2022

Comments

  • gallly
    gallly almost 2 years

    I am doing an xpath search

    page = driver.find_element_by_xpath('//td[@class="mceIframeContainer mceFirst mceLast"]')[1]
    

    This gives me the first class item which I need, in firebug, but apparently python won't allow me to add the [1] to the find function. Is there any workaround? The search returns 2 items, I only want one. Am I approaching this wrong?

  • gallly
    gallly almost 11 years
    thanks!, although this worked in locating the element, I could not get my code to work after, but this is a good answer
  • gallly
    gallly almost 11 years
    oh wow I had no idea it only returns 1 element, this is also a very good answer
  • TehTris
    TehTris almost 11 years
    1. Get google chrome 2. Open webpage that has the stuff on it 3. Right click on the element you want 4. Go to inspect element 5. Right click on selected area in the window that popped up below, and hit 'copy xpath'. Paste that in a notepad, then do the same thing for the other elements, and watch the difference, then you will see what i mean even better.
  • gallly
    gallly almost 11 years
    yeah thanks for the advice. I actually have been doing that, but the particular website im trying is dynamic for every object. Every element I try to copy xpath, it just gives me a dynamic id. I am not sure how to get past that so i just use crappy xpath selections, with text and all XD. When I try to find the xpath without id, its hard because there can be like 400 divs and I have to guess where it is, unless firebug can show me, but firebug always shows me xpath by id