本文介绍如何在 java + selenium 中批量获取商品的评论数(或浏览数),识别数值最大的商品,并精准点击其对应的 `` 链接元素,解决新手常遇的“定位到文本但无法点击”问题。
在电商类页面自动化测试或爬取场景中,常需根据动态指标(如评论数、浏览量、收藏数)筛选目标商品并执行点击操作。你提供的 HTML 结构中,每个商品包裹在
144
13
注意:你原代码中用 //div[@class='AdItem_viewAndFavorite__pjskf']//div[1] 定位第一个 div(即浏览数),这是正确的——但关键在于:该 元素本身不可点击,真正可点击的是其上方最近的 标签。
以下是优化后的完整示例代码(含异常处理与健壮性增强):
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.PageFactory;
import java.util.List;
public class ProductListingPage {
private WebDriver driver;
// 定位所有商品容器(推荐:以 section 为单位,保证结构一致性)
@FindBy(xpath = "//section[contains(@class, 'AdItem_adOuterHolder')]")
private List productSections;
public ProductListingPage(WebDriver driver) {
this.driver = driver;
PageFactory.initElements(driver, this);
}
public SingleProductPage clickProductWithMostViews() {
int maxViews = -1;
WebElement targetLink = null;
for (WebElement
section : productSections) {
try {
// 在当前 section 内查找浏览数(第一个 .AdItem_count__iNDqG)
WebElement viewsElement = section.findElement(
By.xpath(".//div[contains(@class,'AdItem_viewAndFavorite')]/div[1]//span[contains(@class,'AdItem_count')]")
);
String viewsText = viewsElement.getText().trim().replaceAll("[^\\d]", "");
int currentViews = Integer.parseInt(viewsText);
if (currentViews > maxViews) {
maxViews = currentViews;
// ✅ 精准定位:在同一个 section 内找最靠近的 (通常是父级或前序兄弟)
targetLink = section.findElement(By.xpath(".//a[@class='Link_link__J4Qd8' and @href]"));
}
} catch (Exception e) {
// 跳过解析失败的商品(如无浏览数、动态加载未完成等)
continue;
}
}
if (targetLink == null) {
throw new RuntimeException("No product with valid view count found.");
}
targetLink.click();
return new SingleProductPage(driver); // 返回详情页对象
}
} 要点击“评论/浏览数最多”的商品,核心不是“先找数字再反向找链接”,而是以商品区块为最小处理单元,在每个区块内同时提取指标与操作入口。这种结构化遍历方式更符合真实 DOM 层级关系,显著提升脚本鲁棒性与可维护性。掌握此模式后,扩展至按价格排序、按评分筛选等场景也水到渠成。