在此处输入图像描述
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();
}
}
需要打手机,但它正在流行,请帮助纠正
而不是
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();
}
}
使用此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();