-1

I am trying to make selenium click the add to trolley button but there is an error the code which I am using is:

trolley = driver.find_element_by_xpath("//button[@role='button']")
trolley.click()

The inspect element of the button is:

<button class="Buttonstyles__Button-pv6mx8-2 SczzF" data-test="add-to-trolley-button-button" kind="primary" role="button" tabindex="0" type="button" xpath="1" style=""><span><span>Add<span class="sr-only"> </span> to trolley</span></span></button>
undetected Selenium
  • 183,867
  • 41
  • 278
  • 352
  • 2
    We are going to need more information than that. The xpath appears correct. What is the site you are scraping, what is the other code prior to and after that line, what is the expected result, what is the actual result, what is the error...? – goalie1998 Jan 27 '21 at 23:00
  • We need HTML code of section with button and error, u r getting. – IPolnik Jan 27 '21 at 23:59

2 Answers2

0

I was able to find a pythonspot article on clicking a button using selenium (https://pythonspot.com/selenium-click-button/) and they used the function:

trolley = driver.find_elements_by_xpath(`xpath here`)
trolley.click()

The difference between them is this one returns a list over a single element, im not sure why this might work over your method but this is what ive found. Just change that element to elements

Salad
  • 36
  • 6
0

To locate the element you can use either of the following Locator Strategies:

  • Using CSS_SELECTOR:

    driver.find_element(By.CSS_SELECTOR, "button[class^='Buttonstyles__Button'][data-test='add-to-trolley-button-button'] > span > span").click()
    
  • Using XPATH:

    driver.find_element(By.XPATH, "//button[starts-with(@class, 'Buttonstyles__Button') and @data-test='add-to-trolley-button-button']/span/span").click()
    

Ideally, to locate the clickable element you need to induce WebDriverWait for the visibility_of_element_located() and you can use either of the following Locator Strategies:

  • Using CSS_SELECTOR:

    WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "button[class^='Buttonstyles__Button'][data-test='add-to-trolley-button-button'] > span > span"))).click()
    
  • Using XPATH:

    WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//button[starts-with(@class, 'Buttonstyles__Button') and @data-test='add-to-trolley-button-button']/span/span"))).click()
    
  • Note : You have to add the following imports :

    from selenium.webdriver.support.ui import WebDriverWait
    from selenium.webdriver.common.by import By
    from selenium.webdriver.support import expected_conditions as EC
    
undetected Selenium
  • 183,867
  • 41
  • 278
  • 352