'Selenium webdriver not finding add to cart button in Amazon

After selecting a product and opening it in another page Im not able to click on add to cart button in amazon using selenium.



Solution 1:[1]

If you are not switching to other page, Add to card option will not be located. Switch to the opened page and then try to click on the button.

handles = driver.window_handles
driver.switch_to.window(handles[1])
driver.find_element_by_id("add-to-cart-button").click()

If you have done this, share the code you have tried and error you get.

Solution 2:[2]

Without HTML page you are trying to perform, it is difficult to pinpoint exactly. However, I would like to take a stab at it considering these:

  1. Click on product in home page
  2. Product opens in a new tab window
  3. Click on add to cart

P.S: I will write it using Java since you haven't mentioned on the language being used. Will be similar in others as well

Click on product in home page

List <Webelement> productCheck = driver.findElements(By.xpath("<xpath of the product>"))
if (productCheck.size() == 0){
// do something
else {
driver.findElement(By.xpath("<xpath of the product>")).click();
}

Product opens in a new tab window and Click on add to cart

String parent = driver.getWindowHandle();
List<String> windows = new ArrayList<String>(driver.getWindowHandles());
driver.switchTo().window(windows.get(1));

// Inside the tab window

List <WebElement> addtoCartButton = driver.findElements(By.xpath("<xpath of Add to cart button>"));
if (addtoCartButton.size() == 0 ) {
// do something
else {
driver.findElement(By.xpath("<xpath of Add to cart button>")).click();
}


// do whatever you want in the new tab and if you want to switch back then:

driver.switchTo().window(parent);

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 pmadhu
Solution 2 Adarsh Kumar GM