我正在测试一个脚本来查找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'
将路径拆分为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
所以我试过这样的事情:
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)
它不工作请帮忙! 如果问题不明确请评论(新在这里)
答案 0 :(得分:0)
如果您只想获得另一个div
的子div
个节点的数量,您可以实现以下内容:
parent_div = driver.find_element_by_xpath("//div")
count_of_divs = len(parent_div.find_elements_by_xpath("./div"))
或直接
count_of_divs = len(driver.find_elements_by_xpath("//div/div"))
请注意,要选择所需的div
,您应该使用一些predicate来确保您的XPath是唯一的
如果您想选择 last div child ,您也可以尝试
driver.find_element_by_xpath("//div/div[last()]")