Home > Mobile >  Get specific occurrence Python Selenium
Get specific occurrence Python Selenium

Time:01-24

I am automating a website, and it has multiple searchboxes with the same title, class, etc. It usually occurs 2 or 3 times on every page. Is there a way in which I can tell Selenium to only use the 2nd or 3rd occurrence?

I currently have this:

driver.find_element(By.XPATH, './/*[@title = "Searchbox"]').click()

And

driver.find_element(By.XPATH, './/*[@title = "Searchbox"]').send_keys(i)

It currently clicks the first searchbox and types number i, but I want Selenium to do this for any other searchbox with the same html.

Thanks!

CodePudding user response:

To get some element by it's occurrence using xpath just wrap the xpath in (<your xpath>)[number] where number is the element occurrence number.

For click the second one:

driver.find_element(By.XPATH, '(.//*[@title = "Searchbox"])[2]').click()

CodePudding user response:

Ideally your locator strategy should identify each and every WebElement uniquely within the DOM Tree.

As your Locator Strategy identifies 2 or 3 elements on every page, you need to construct a more canonical locator. However the following line of code:

driver.find_element(By.XPATH, './/*[@title = "Searchbox"]')

will always select the first matching element.


To click on the second and third matching element, you can use the following locator strategies:

  • To click on second match:

    driver.find_element(By.XPATH, "(.//*[@title = "Searchbox"])[1]").click()
    
  • To click on third:

    driver.find_element(By.XPATH, "(.//*[@title = "Searchbox"])[2]").click()
    

CodePudding user response:

As a last resort you can use xpath indexing:

if this .//*[@title = "Searchbox"] represent 1/3 nodes or 1/2 nodes

you can simply change it to

(.//*[@title = "Searchbox"])[2] 

and use it like this:

driver.find_element(By.XPATH, "(.//*[@title = 'Searchbox'])[2]").send_keys(i)

to represent 2nd node

or [3] to represent 3rd node.

(.//*[@title = "Searchbox"])[3]

and so on....

This is not recommended but can be used as a last resort.

  •  Tags:  
  • Related