如何使用 python selenium webdriver 获取 div 标签内的 div 标签总数

Aya*_*lik 2 arrays selenium xpath python-3.x selenium-webdriver

我正在测试一个脚本来查找 div 标签内的 div 标签的数量,这样做的原因...是为了获取完整路径内的最后一个 div 编号( div[last div] )。

div 的完整路径如下:

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'
Run Code Online (Sandbox Code Playgroud)

将路径分成 4 部分

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
Run Code Online (Sandbox Code Playgroud)

所以我尝试了这样的事情:

    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)
Run Code Online (Sandbox Code Playgroud)

它不起作用,请帮助!如果问题不清楚请评论(这里是新的)

And*_*son 6

如果您只是想获取div另一个 的子节点的数量div,您可以实现如下所示:

parent_div = driver.find_element_by_xpath("//div")
count_of_divs = len(parent_div.find_elements_by_xpath("./div"))
Run Code Online (Sandbox Code Playgroud)

或直接

count_of_divs = len(driver.find_elements_by_xpath("//div/div"))
Run Code Online (Sandbox Code Playgroud)

请注意,要选择必需的,div您应该使用一些谓词来确保您的 XPath 是唯一的

如果你想选择最后一个 div 子元素,你也可以尝试

driver.find_element_by_xpath("//div/div[last()]")
Run Code Online (Sandbox Code Playgroud)