Ayan Malik
Ayan Malik

Reputation: 23

How to get total count of div tags inside a div tag using python selenium webdriver

I am testing a script to find the number of div tags inside a div tag, reason to do this...is to get the last div number ( div[last div] ) inside a full path.

full path of div is like :

full_path = '//*[@id="main"]/div[2]/div/div # continue line
/div[2]/div[i want the total div count here]/div/ # continue line
div/div[2]/div/div'

split the path to 4 section

full_path = '//*[@id="main"]/div[2]/div/div/div[2]/div[14]/div/div/div[2]/div/div'

half_path1 = '//*[@id="main"]/div[2]/div/div/div[2]'

half_path_with_slash = '//*[@id="main"]/div[2]/div/div/div[2]/'

second_half_path = '/div/div/div[2]/div/div'


print ('going to search')

test_path = wait.until(EC.presence_of_element_located((By.XPATH,half_path)))

count = driver.select_list(:id=> 'div').options.count

print ('searching')

print (count) # not working

so i tried something like this :

    waitof = WebDriverWait(driver = driver, timeout = 9)

    array = [] # to collect the div count

    for i in array:

        test_path = waitof.until(EC.presence_of_element_located((By.XPATH,half_path1)))
        print('div loaded')

        test_pathx = driver.find_element_by_xpath(slash_path)
        array.append(text_pathx)
        print ('first loop')
        for i in test_pathx:
            print ('second loop')
            loop_path = driver.find_element_by_xpath(just_path1 +'div[%d]' % (i))
            div_elements.append[i]
            print(div_elements[i])

    awesome_full_path = ('//*[@id="main"]/div[2]/div/div/div[2]/div[%d]
/div/div/div[2]/div/div' % div_elements)

its not working please help!!! if the question is not clear please comment (new here)

Upvotes: 2

Views: 5899

Answers (1)

Andersson
Andersson

Reputation: 52665

If you simply want to get count of child div nodes of another div, you can implement something like below:

parent_div = driver.find_element_by_xpath("//div")
count_of_divs = len(parent_div.find_elements_by_xpath("./div"))

or directly

count_of_divs = len(driver.find_elements_by_xpath("//div/div"))

Note that to select required div you should use some predicate to be sure that your XPath is unique

If you want to select last div child you can also try

driver.find_element_by_xpath("//div/div[last()]")

Upvotes: 6

Related Questions