如何用Selenium统计父<div>下的子<div>数量?附代码疑问
如何用Selenium统计父
下的子
数量
嘿,我来帮你搞定这个问题!其实你的现有代码已经离答案很近了,只是没用到列表的size()方法而已,另外我也会给你更精准的实现方式,避免定位到无关元素。
方法一:基于你现有代码直接统计
你当前的代码已经通过findElements获取到了目标子
的列表,只需要调用列表的
size()方法就能得到数量:List<String> productName = new ArrayList<String>(); List<WebElement> divElement = driver.findElements(By.cssSelector("div.list-group-item.llamada-ajax-TA.text-center")); // 新增统计数量的代码 int childDivCount = divElement.size(); System.out.println("父div下的子div数量:" + childDivCount); for(WebElement w : divElement) { productName.add(w.getText()); } System.out.print(productName);
方法二:精准定位父元素后统计子元素
如果担心当前选择器会匹配到页面其他地方的
,可以先定位到父
,再在父元素的上下文里查找子
,这样更准确:
// 1. 先定位到父div,替换成你实际的父元素选择器 WebElement parentDiv = driver.findElement(By.cssSelector("div.your-parent-container-selector")); // 2. 查找父div下的直接子div(用>表示直接子元素,若要包含所有层级的后代div,去掉>即可) List<WebElement> childDivs = parentDiv.findElements(By.cssSelector("> div")); // 3. 获取子div数量 int count = childDivs.size(); System.out.println("父div下的子div数量:" + count);
注意事项:处理动态加载元素
你的选择器里有llamada-ajax-TA,看起来这些子div是AJAX动态加载的,为了确保统计结果准确,建议使用显式等待等待元素加载完成:
WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10)); // 等待所有目标子div可见 List<WebElement> childDivs = wait.until( ExpectedConditions.visibilityOfAllElementsLocatedBy( By.cssSelector("div.list-group-item.llamada-ajax-TA.text-center") ) ); int count = childDivs.size(); System.out.println("子div数量:" + count);
内容的提问来源于stack exchange,提问作者Billy Martinez
相关产品推荐
相关产品推荐

