wezzo
wezzo

Reputation: 49

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

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

Upvotes: 0

Views: 318

Answers (2)

Sonali Das
Sonali Das

Reputation: 1026

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()

Upvotes: 0

Amir Aref
Amir Aref

Reputation: 401

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)

Upvotes: 1

Related Questions