Home > Mobile >  how to select more than one element with almost the same xpath?
how to select more than one element with almost the same xpath?

Time:02-27

i have some elements with the following xpath format:

//*[@id="dashboardRoot"]/span/div/div/div/div[1]/div/div/div[1]/main/div[2]/div[2]/div[1]/div/div/table/tbody/tr[i]

where i = 1,2,3,4,....etc

How to select an element every time in a loop?

i tried this way:

for i in range(5):
    
    try:
        
        xpath = '//*[@id="dashboardRoot"]/span/div/div/div/div[1]/div/div/div[1]/main/div[2]/div[2]/div[1]/div/div/table/tbody/tr["i 1"]'

        select_card = browser.find_element_by_xpath(xpath).click()

but it works with the first element every time and don't move tho the next one.

thanks in advance

CodePudding user response:

to place the i value in the string, you must put it in the string format as below :

xpath = f'//*[@id="dashboardRoot"]/span/div/div/div/div[1]/div/div/div[1]/main/div[2]/div[2]/div[1]/div/div/table/tbody/tr[{i 1}]'

or

xpath = '//*[@id="dashboardRoot"]/span/div/div/div/div[1]/div/div/div[1]/main/div[2]/div[2]/div[1]/div/div/table/tbody/tr[{}]'.format(i 1)

CodePudding user response:

Instead of find element,use find elements.your code should be this:

xpath = '//*[@id="dashboardRoot"]/span/div/div/div/div[1]/div/div/div[1]/main/div[2]/div[2]/div[1]/div/div/table/tbody/tr'
elements= browser.find_elements_by_xpath(xpath)
for element in elements:
    element.click()
  • Related