使用Selenium Java获取Supreme官网商品页li元素失败求助
解决Supreme商品页li元素获取失败的问题
嘿,看你在尝试用Selenium抓取Supreme官网商品页的li元素时碰了壁,我来帮你捋捋常见问题,给你可行的解决方案:
一、头号坑:页面还没加载完就急着找元素
Supreme的页面是动态渲染的,刚调用driver.get()就去获取元素,大概率页面还没加载完全,自然找不到目标li。这时候显式等待是必须的,等元素加载出来再动手。
二、得用对元素定位器
先打开浏览器开发者工具(F12)看看Supreme商品页的结构:商品列表的li一般在#shop-scroller这个容器下面,或者带有特定的类名(比如shop-item)。别瞎写定位器,得对着实际页面结构来。
三、给你补全后的完整代码
把你没写完的部分补上,加上等待和正确的定位逻辑:
public static void main(String[] args) throws Exception { // Windows路径要注意双反斜杠转义,别写错了 System.setProperty("webdriver.chrome.driver", "Your\\ChromeDriver\\Path"); ChromeOptions options = new ChromeOptions(); options.setHeadless(false); // 加俩参数防反爬,避免被Supreme识别成自动化工具 options.addArguments("--disable-blink-features=AutomationControlled"); options.addArguments("user-agent=Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36"); WebDriver driver = new ChromeDriver(options); driver.get("http://www.supremenewyork.com/shop/"); // 显式等待10秒,直到所有li元素都加载出来 WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10)); List<WebElement> allElements = wait.until( ExpectedConditions.presenceOfAllElementsLocatedBy(By.cssSelector("#shop-scroller li")) ); // 测试下结果,看看有没有抓到 System.out.println("一共找到" + allElements.size() + "个li元素"); for(WebElement item : allElements) { System.out.println(item.getText()); } driver.quit(); }
四、额外提醒几个点
- 路径别写错:Windows系统下ChromeDriver的路径必须用双反斜杠
\\,单斜杠会报错。 - 防反爬要做:Supreme有反爬检测,默认的Selenium配置很容易被识别,所以加了禁用自动化检测和自定义User-Agent的参数,模拟正常浏览器访问。
- 定位器要灵活:如果上面的CSS选择器不好使,自己去开发者工具里找对应的选择器(比如XPath),替换掉
By.cssSelector()里的内容就行。
内容的提问来源于stack exchange,提问作者Irantwomiles




