有人要求我自动化在线购物网站的代码,将商品添加到购物车并结账,但我陷入了困境。
该项目的图像不断变化,因此它的 xpath 也不断变化。我正在使用操作来执行鼠标悬停功能,但它不起作用并且出现错误
Exception in thread "main" org.openqa.selenium.TimeoutException: Timed out after 50 seconds waiting for visibility of element located by By.xpath: html/body/
请找到下面的代码:
w.get("http://www.provogue.com/new-arrivals");
WebDriverWait wait= new WebDriverWait(w,30);
Actions action = new Actions(w);
WebElement elem = w.findElement(By.xpath("html/body/div[2]/div/div/div[2]/div/div[2]/div[2]/ul[1]/li[2]/div[2]/a[1]/div/img[1]"));
wait.until(ExpectedConditions.presenceOfElementLocated(By.xpath("html/body/div[2]/div/div/div[2]/div/div[2]/div[2]/ul[1]/li[2]/div[2]/a[1]/div/img[1]")));
action.moveToElement(elem).click();
action.build().perform();
最佳答案
上述代码中使用的定位器不正确。要单击第一行中的第二个商品并将其添加到购物车,请使用以下代码
driver.get("http://www.provogue.com/new-arrivals");
driver.manage().timeouts().implicitlyWait(10,TimeUnit.SECONDS);
//click on the first row ul[1] second item li[2]
driver.findElement(By.xpath("//div[@class='category-products']/ul[1]/li[2]/div[2]/a/img")).click();
//wait for the iframe to load and then switch to it
WebDriverWait wait = new WebDriverWait(driver, 30000);
wait.until(ExpectedConditions.frameToBeAvailableAndSwitchToIt((By
.className("fancybox-iframe"))));
//select size and then
//click on Add to cart button
driver.findElement(By.xpath("//button[@title='Add to Cart']")).click();
//switch back to default content
driver.switchTo().defaultContent();
编辑
driver.get("http://www.provogue.com/new-arrivals");
driver.manage().timeouts().implicitlyWait(10,TimeUnit.SECONDS);
//click on the first row ul[1] second item li[2]
Actions actions = new Actions(driver);
WebElement productImage = driver.findElement(By.xpath("//div[@class='category-products']/ul[1]/li[2]/div[2]/a[@class='product-image']"));
actions.moveToElement(productImage).perform();
WebElement ViewLink = driver.findElement(By.xpath("//div[@class='category-products']/ul[1]/li[2]/div[2]/a[@class='fancybox']"));
actions.moveToElement(ViewLink);
actions.click();
actions.perform();
//wait for the iframe to load and then switch to it
WebDriverWait wait = new WebDriverWait(driver, 30000);
wait.until(ExpectedConditions.frameToBeAvailableAndSwitchToIt((By
.className("fancybox-iframe"))));
//select size and then
//click on Add to cart button
driver.findElement(By.xpath("//button[@title='Add to Cart']")).click();
//switch back to default content
driver.switchTo().defaultContent();
}
我已经测试了上面的代码,它工作正常
希望这对您有帮助。如果您有任何疑问,请检查并回复
关于java - 如何在selenium webdriver中定位动态变化的图像?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32633563/