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.
Solutions to Target Only Top-Level Menu Links
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

