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

Java版Selenium循环打印页面商品名称失败问题求助

解决Selenium循环无法打印商品名称的问题

嘿,我来帮你排查这个问题!你说程序能正常导航到页面,但循环就是不执行,结合你给出的代码片段,大概率是踩了这几个常见的Selenium坑:

1. 导航步骤不完整,没进入商品列表页

你代码的最后一行是driver2.findElement(By.xpath("//*[@id='riotbar-navbar']/a[2]"))....,看起来没完成点击操作?要知道,得先点击导航栏的商店选项(比如这个a[2]对应的就是Store),真正进入商品列表页面,后续的循环才有元素可遍历啊!

2. 缺少等待机制,元素还没加载就执行循环

Selenium的执行速度远快于网页渲染速度,直接去查找商品元素时,页面可能还没加载完成,导致获取不到元素集合,循环自然没东西可输出。必须加显式等待,确保目标元素加载完成后再执行后续操作。

3. 错误使用findElement()而非findElements()

要遍历所有商品,你需要用findElements()(复数形式)获取页面上所有匹配的商品元素集合;如果用findElement(),只会拿到第一个匹配元素,根本触发不了循环遍历的逻辑。


修正后的示例代码

我结合你的场景写了完整的可运行代码,你可以参考调整:

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;

import java.time.Duration;
import java.util.List;

public class LoLProductScraper {
    public static void main(String[] args) {
        // 假设你之前配置了ChromeOptions
        ChromeOptions c = new ChromeOptions();
        WebDriver driver2 = new ChromeDriver(c);
        
        try {
            driver2.get("https://na.leagueoflegends.com/en/");
            driver2.manage().window().maximize();

            // 点击continue按钮进入主页
            driver2.findElement(By.cssSelector("a.continue")).click();

            // 显式等待导航栏的商店链接可点击,然后点击进入
            WebDriverWait wait = new WebDriverWait(driver2, Duration.ofSeconds(15));
            WebElement storeNavLink = wait.until(
                ExpectedConditions.elementToBeClickable(By.xpath("//*[@id='riotbar-navbar']/a[2]"))
            );
            storeNavLink.click();

            // 等待商品列表元素加载完成(这里的选择器需要你替换成页面真实的商品名选择器)
            wait.until(
                ExpectedConditions.presenceOfElementLocated(By.cssSelector(".product-name"))
            );
            // 获取所有商品名称元素的集合
            List<WebElement> allProductNames = driver2.findElements(By.cssSelector(".product-name"));

            // 遍历打印每个商品名称
            for (WebElement product : allProductNames) {
                String productText = product.getText().trim();
                if (!productText.isEmpty()) { // 过滤空文本
                    System.out.println("商品名称:" + productText);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            // 无论成功失败,都关闭浏览器
            driver2.quit();
        }
    }
}

额外注意事项

  • 替换元素选择器:我代码里用的.product-name是示例,你需要打开浏览器开发者工具(F12),找到页面上商品名称对应的真实CSS选择器或XPath,替换进去。
  • 处理弹窗:如果页面有Cookie同意弹窗、年龄验证弹窗等,要先添加代码关闭这些弹窗,避免它们遮挡元素导致定位失败。
  • 检查iframe:如果商品列表是在<iframe>标签里,你需要先切换到iframe才能定位元素,用法是:driver2.switchTo().frame("iframe的id或name");,操作完再切回主文档:driver2.switchTo().defaultContent();。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.22 09:47:56