Find element by position using xpath

My selenium driver finds about 13 li elements. However, the following does not work, giving element not found error:

driver.find_element_by_xpath('//li[0]')

But, this works correctly:

driver.find_elements_by_xpath('//li')[0]

I thought these are the same, although I would prefer the first approach to work. What is going on here?

1 answer

  • answered 2018-03-13 21:47 Ian Lesperance

    Python is zero-indexed, but XPath is one-indexed:

    The first position is 1.

    As a result, the following are equivalent:

    driver.find_elements_by_xpath('//li')[0]
    driver.find_element_by_xpath('(//li)[1]')