Home > Software engineering >  Message: no such element: Unable to locate element Selenium Python:{"method":"xpath&q
Message: no such element: Unable to locate element Selenium Python:{"method":"xpath&q

Time:10-18

I am trying to click input button on webpage

<input type="button" id="add-to-wishlist-button-5"  value="Add to wishlist" data-productid="5" onclick="AjaxCart.addproducttocart_details('/addproducttocart/details/5/2', '#product-details-form');return false;">

using such code:

driver = webdriver.Edge(executable_path='C:\\Program Files (x86)\\Microsoft\\Edge\\Application\\msedgedriver.exe')
driver.get('https://demowebshop.tricentis.com/')
driver.maximize_window()

category = driver.find_element(By.LINK_TEXT,"Apparel & Shoes")
category.click()


links = driver.find_elements(By.CSS_SELECTOR,"div.product-grid a")
random.choice(links).click()
wish_list = browser.find_element(By.XPATH,"//input[@value='Add to wishlist']")
wish_list.click()

but at the line

wish_list = browser.find_element(By.XPATH,"//input[@value='Add to wishlist']")

getting error as title of this question

CodePudding user response:

For the few on the product list, there is no "Add to Wish" button available for a few products. So you have to do proper error handling for no element.

from selenium.common.exceptions import NoSuchElementException

try:
    wish_list = browser.find_element(By.XPATH,"//input[@value='Add to wishlist']")
    wish_list.click()
except NoSuchElementException:  # Error catch here
    print('No Add to wish button available.')

CodePudding user response:

I see 2 issues here not covered by previous answer:

  1. All your code using driver while for the last element you are using browser. This may be a typo, but with it your code will never work.
  2. You need to add a delay to wait for elements clickability.
    I did not use random.choice, just to see that the code is basically working.
    So, the following code is working stable:
from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
options = Options()
options.add_argument("start-maximized")

webdriver_service = Service('C:\webdrivers\chromedriver.exe')
driver = webdriver.Chrome(service=webdriver_service, options=options)
url = 'https://demowebshop.tricentis.com/'
driver.get(url)
wait = WebDriverWait(driver, 10)

wait.until(EC.element_to_be_clickable((By.LINK_TEXT, "Apparel & Shoes"))).click()
wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR, "div.product-grid a"))).click()
wait.until(EC.element_to_be_clickable((By.XPATH, "//input[@value='Add to wishlist']"))).click()
  • Related