Selenium使用XPath定位兄弟节点点击Mobiles模块错误,求代码修正
问题根因
- 原XPath使用索引定位兄弟节点,完全依赖导航栏元素的固定排序,亚马逊印度站导航栏会根据用户地域、活动动态调整展示项顺序,或者存在隐藏的占位元素,索引值容易失效
- 你使用的
following-sibling::a[2]取的是当前节点之后第2个a标签,当前nav-xshop下第一个a标签之后第1个就是Mobiles模块,第2个正好是Fashion模块,所以会出现点错的情况
修正方案
优先使用文本匹配定位元素,不依赖节点顺序,稳定性最高,修改XPath为//div[@id='nav-xshop']//a[text()='Mobiles']即可。
修正后完整代码
import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.chrome.ChromeDriver; public class Demo { public static void main(String[] args) { System.setProperty("webdriver.chrome.driver","C:\\Users\\5558\\Desktop\\Selenium\\chromedriver.exe" ); WebDriver driver=new ChromeDriver(); driver.get("https://www.amazon.in"); //在浏览器中打开目标网址 System.out.println(driver.getTitle()); // 替换为文本匹配的XPath driver.findElement(By.xpath("//div[@id='nav-xshop']//a[text()='Mobiles']")).click(); } }
如果你需要练习兄弟节点定位语法,只要把原来的索引从2改成1即可,对应XPath为//div[@id='nav-xshop']/a[1]/following-sibling::a[1],但这种方式稳定性远低于文本匹配,不推荐生产环境使用。
内容的提问来源于stack exchange,提问作者Shreyansh Singh
相关产品推荐
相关产品推荐

