You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Selenium中能否统计非Select/Table结构的动态含链接地点列表条目数?

你的理解不正确,完全可以统计显示的地点数量

从你提供的HTML代码来看,所有地点链接都被包裹在id="divPlaces"的容器内,每个地点对应一个带有<a>标签的子元素(嵌套在class="blksmlr smlhead sngline"的div里)。Selenium完全可以通过定位这些元素来统计数量,具体方法如下:

核心思路

先定位到所有符合条件的地点元素,再通过获取元素列表的长度得到数量。这里需要注意必须等待动态列表加载完成,否则可能会统计到0个元素(因为页面还没渲染完)。

具体实现示例

Python 版本

from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC

# 显式等待,确保动态列表加载完成(最长等待10秒)
wait = WebDriverWait(driver, 10)
# 定位所有地点链接元素
place_elements = wait.until(
    EC.presence_of_all_elements_located((By.CSS_SELECTOR, "#divPlaces .blksmlr a"))
)

# 统计数量
place_count = len(place_elements)
print(f"当前显示的地点数量: {place_count}")

Java 版本

import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.openqa.selenium.support.ui.ExpectedConditions;
import java.time.Duration;
import java.util.List;

// 显式等待动态元素加载
WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10));
List<WebElement> placeElements = wait.until(
    ExpectedConditions.presenceOfAllElementsLocatedBy(
        By.cssSelector("#divPlaces .blksmlr a")
    )
);

// 获取数量
int placeCount = placeElements.size();
System.out.println("当前显示的地点数量: " + placeCount);

额外说明

  • 你也可以选择定位包含地点的父div(By.cssSelector("#divPlaces .blksmlr.smlhead.sngline")),再获取列表长度,结果是一样的。
  • 显式等待是关键:因为列表是动态加载的,直接用findElements可能会在元素未渲染时执行,导致得到错误的数量。

内容的提问来源于stack exchange,提问作者ViTest

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.13 06:35:26