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

Selenium获取顶部菜单正确链接数量的技术问题

Hey there! Let's break down why your current XPath is returning 17 elements instead of the 6 you expect, and fix it to target only the top-level menu items (Home, Shop, Cart, My Account, Test Pages, How to Use).

What's Wrong With the Original XPath?

Your current code uses:

List<WebElement> home_menu=br.driver.findElements(By.xpath("//a[contains(@href,'http://test1.absofttrainings.com/')]/following-sibling::*//a"));

The issue here is the following-sibling::*//a part. This selects all descendant <a> tags from every sibling element that comes after your initial anchor. That means it's pulling in links from dropdown sub-menus too, which explains the extra 11 elements beyond your 6 valid top-level items.

We need to adjust the XPath to focus specifically on the first-level menu items, ignoring nested sub-menus. Here are a few reliable approaches based on common navigation DOM structures:

1. Target the Top-Level Menu Container Directly

Most sites wrap top-level menus in a dedicated <ul> (or <nav>) with a unique class like main-navigation or nav-menu. Use this to select only direct child <li> elements and their <a> tags:

// Assuming the top-level menu is in a <ul> with class "main-navigation"
List<WebElement> topMenu = br.driver.findElements(By.xpath("//ul[contains(@class, 'main-navigation')]/li/a"));
System.out.println(topMenu.size()); // Should output 6

2. Exclude Sub-Menu Links

If you're unsure of the container class, you can explicitly exclude links that live inside sub-menus. This works if sub-menus have a class like sub-menu:

List<WebElement> topMenu = br.driver.findElements(By.xpath("//li[contains(@class, 'menu-item') and not(ancestor::ul[contains(@class, 'sub-menu')])]/a"));

This selects <a> tags from <li> items that are not nested inside a sub-menu <ul>.

3. Target Siblings of the Home Menu Item

Since you know "Home" is one of the top-level items, you can use it as a reference to grab its sibling top-level links (plus Home itself):

// Get Home plus all sibling top-level menu links
List<WebElement> topMenu = br.driver.findElements(By.xpath("//a[text()='Home']/parent::li/following-sibling::li/a | //a[text()='Home']"));

The | operator combines two XPath queries: one for Home, and one for all its sibling <li> links.

How to Verify Your XPath

Before updating your code, test the XPath in your browser's developer tools:

  • Press F12 to open DevTools
  • Go to the Console tab
  • Run $x("your-xpath-here") to see which elements are selected. This lets you tweak the XPath until it only returns the 6 top-level items.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 08:07:11