Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Identifying the first element on the page

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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]")

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading