0

I am attempting to click a button using an XPath but I am unable to locate the element. Complete noob here.

Here is the button element I copied:

  <button _ngcontent-ygw-c218="" class="btn"><span _ngcontent-ygw-c218="" translate="">SHOW ALL</span></button>

Here is my programming:

 ShowAll =driver.find_element_by_xpath('//*[@id="app-SelectComponents"]/div[1]/button[1]')
 ShowAll.click()

I have tried the following solution I found online to no avail (I've also replaced the 'btn' with 'SHOW ALL', no luck there):

 driver.switch_to.frame(driver.find_element_by_name('btn'))
 ShowAll =driver.find_element_by_xpath('//*[@id="app-SelectComponents"]/div[1]/button[1]')
 ShowAll.click()
 driver.switch_to.default_content()

Much appreciated.

EDIT: Here is a picture for reference. What am I doing wrong or what I can do to work around this issue?

HTML for reference

undetected Selenium
  • 183,867
  • 41
  • 278
  • 352
JayJay
  • 1
  • 1

2 Answers2

0

You need to add time to make sure the element is available before asking selenium to pick it. Try this:

import time
driver.switch_to.frame(driver.find_element_by_name('btn'))
time.sleep(5) #you can change the 5 depending on the number that works
ShowAll =driver.find_element_by_xpath('//*[@id="app-SelectComponents"]/div[1]/button[1]').click()
driver.switch_to.default_content()
Babatunde Mustapha
  • 2,131
  • 20
  • 21
  • I have tried this. I receive the following error: selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {"method":"css selector","selector":"[name="btn"]"} – JayJay Jan 13 '22 at 16:02
0

The element with the text as SHOW ALL is within an <iframe> so you have to:

  • Induce WebDriverWait for the desired frame to be available and switch to it.

  • Induce WebDriverWait for the desired element to be clickable.

  • You can use either of the following Locator Strategies:

    • Using CSS_SELECTOR:

      WebDriverWait(driver, 20).until(EC.frame_to_be_available_and_switch_to_it((By.CSS_SELECTOR,"iframe#iParts")))
      WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "button.btn > span[translate]"))).click()
      
    • Using XPATH:

      WebDriverWait(driver, 20).until(EC.frame_to_be_available_and_switch_to_it((By.XPATH,"//iframe[@id='iParts']")))
      WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//button[@class='btn']/span[text()='SHOW ALL']"))).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
    

Reference

You can find a couple of relevant discussions in:

undetected Selenium
  • 183,867
  • 41
  • 278
  • 352