首页 > 解决方案 > 使用 selenium ,我试图在兄弟姐妹中使用 x 路径从一个元素移动到另一个元素

问题描述

在此处输入图像描述

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"); //url in the browser
        System.out.println(driver.getTitle());
        driver.findElement(By.xpath("//div[@id='nav-xshop']/a[1]/following-sibling::a[2]")).click();
}
}

需要打手机,但它正在流行,请帮助纠正

标签: seleniumselenium-webdriverautomated-testsbrowser-automationtestautomationfx

解决方案


代替

driver.findElement(By.xpath("//div[@id='nav-xshop']/a[1]/following-sibling::a[2]")).click();

使用此定位器:

driver.findElement(By.xpath("//a[contains(@href,'mobile-phones')]")).click();

您还应该在此处添加显式等待,因此您的代码应如下所示:

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();
WebDriverWait wait = new WebDriverWait(driver, 30);
driver.get("https://www.amazon.in"); //url in the browser
System.out.println(driver.getTitle());
wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//a[contains(@href,'mobile-phones')]")));
driver.findElement(By.xpath("//a[contains(@href,'mobile-phones')]")).click();
}
}

推荐阅读