0

在此处输入图像描述

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();
}
}

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

4

2 回答 2

0

代替

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();
}
}
于 2021-06-28T11:59:13.097 回答
0

使用这个css_selector

a[href^='/mobile-phones/b/']

像下面这样使用它:

 driver.findElement(By.cssSelector("a[href^='/mobile-phones/b/']")).click();

xpath将是:

//a[contains(@href, '/mobile-phones/b/')]

像这样使用它:

driver.findElement(By.xpath("//a[contains(@href, '/mobile-phones/b/')]")).click();
于 2021-06-28T12:28:21.780 回答