I use python with selenium and I am using the following to identify the 2 web elements on my page:
driver.find_element(By.XPATH("//a[contains(@href, '/checkout')]"))
I am trying to select/identify the first one using:
"//a[contains(@href, '/checkout')][0]"
For some reason it does not work. Please help. Thanks
>Solution :
- To identify the first matching element, you can use the find_elements method instead, and then access the first element of the returned list.
elements = driver.find_elements(By.XPATH, "//a[contains(@href,
‘/checkout’)]")
first_element = elements[0]
- Alternatively, you can use the find_element method with the find_elements locator strategy to achieve the same result in a single line:
first_element = driver.find_element(By.XPATH, "(//a[contains(@href,
‘/checkout’)])[1]")