3

I just want to access a xpath. But when I'm search this in inspect menu it finding 5 result. I want to access one of them not 5. How can I do it with index number? like...

xpath = "//a[@role='button']" # 5 elements available with this xpath
modified_xpath = "//a[@role='button'][2]" # I'm trying with the index number.
driver.find_element_by_xpath(modified_xpath).click() # But It's not working.

It's not working!

3
  • find_elements_by_xpath returns a list, remove the index lookup in the xpath and index into the returned list? driver.find_elements_by_xpath(modified_xpath)[2] Commented Jun 15, 2021 at 5:43
  • What is the error ? Share HTML or URL of the page Commented Jun 15, 2021 at 5:47
  • showing this errorselenium.common.exceptions.InvalidSelectorException: Message: invalid selector: Unable to locate an element with the xpath expression //a[@role='button'] because of the following error: SyntaxError: Failed to execute 'evaluate' on 'Document': The string '//a[@role='button']' is not a valid XPath expression. Commented Jun 15, 2021 at 6:03

1 Answer 1

2

You can do it like this code--

    xpath = "//a[@role='button']" 
    xpaths = driver.find_elements_by_xpath(xpath)
    xpaths[2].click()

Hope it will work.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.