Search code examples
pythonselenium-webdriverweb-scrapingxpathcheckout

I automated the process to search an item in Amazon. However I cannot add the item to cart. ElementNotFound Exception is being raised. Any tips?


from selenium import webdriver 
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.by import By 
from selenium.webdriver.support.ui import WebDriverWait 
from selenium.webdriver.support import expected_conditions as EC
import time

global browser 
browser= webdriver.Chrome()
browser.get("https://www.google.com") 
wait = WebDriverWait(browser,45)
search = browser.find_element(By.NAME,"q") 
search.send_keys("Amazon")
search.send_keys(Keys.RETURN) 
wait.until(EC.element_to_be_clickable((By.PARTIAL_LINK_TEXT,"amazon.in"))).click()
search = wait.until(EC.presence_of_element_located((By.ID,"twotabsearchtextbox"))) 
search.send_keys("PS5") 
search.send_keys(Keys.RETURN)
wait.until(EC.presence_of_element_located((By.LINK_TEXT,"Sony PS5 PlayStation Console"))).click()
try:
add_to_cart_button = wait.until(EC.presence_of_element_located((By.XPATH, '//*[@id="add-to-cart-button"]')))
add_to_cart_button.click()
except Exception as e:
print("Error:", e)
finally:
browser.quit()

time.sleep(2)
browser.quit()

'''I did try Explicit Time to search for an element, as it gives the time to locate the element. I started to use the XPATH too but it doesn't work in any way. Everything goes good when it comes to add to cart button the web driver can't find the element.'''


Solution

  • You can't get element, because line

    wait.until(EC.presence_of_element_located((By.LINK_TEXT,"Sony PS5 PlayStation Console"))).click()
    

    opens new tab.

    Selenium doesn't automatically switch contexts, so you should switch context to new tab after click.

    #previous code
    window_handles = browser.window_handles
    new_window_handle = window_handles[-1]
    browser.switch_to.window(new_window_handle)
    add_to_cart_button = wait.until(EC.presence_of_element_located((By.ID, 'add-to-cart-button')))
    add_to_cart_button.click()
    

    Btw, you can access direct amazon link and not to search it in Google.