'Accept consent condition if not found

I am having trouble coming with a condition to skip accepting consent whenever its not there. When I am working with our environments there is no need to accept consent and I need to make the function in a way it will just skip whenever its not visible. Tried many ways around it, try / catch, except NoSuchElement but I just get error that I cannot click element that doesnt exist.

the function looks like this - finding the element is a bit sketchy, I had troubles accepting the consent at all and had to ask here on the forum how to do it.

def acceptConsent(driver):
  time.sleep(2)
  try:
    element = driver.execute_script(
      """return document.querySelector('#usercentrics-root').shadowRoot.querySelector("button[data-testid='uc-accept-all-button']")""")
  except NoSuchElementException:
    return

  except TimeoutException:
    pass
  try:
    element.click()
  except TimeoutException:
    pass
  except NoSuchElementException:
    return

something that I tried is this : condition that if element doesnt exist it should just pass and continue. Works whenever theres not consent to be accepted, but doesnt work on production, it acts as theres no popup and skips accepting it

def acceptConsent(driver):
  time.sleep(2)
  try:
    element = driver.execute_script(
      """return document.querySelector('#usercentrics-root').shadowRoot.querySelector("button[data-testid='uc-accept-all-button']")""")
    if element !=0:

      pass

    else:
      element.click()

  except NoSuchElementException:
      pass    

  except TimeoutException:
    pass

If anyone has any thoughts how to solve it I am happy to hear it. The website I am working with is https://www.fischer.cz/

Thanks to anyone who responds in advance!



Solution 1:[1]

Just use only the try..except block. If element present it will click and move to next and if not present this will go to exception.

try:
  element = driver.execute_script("""return document.querySelector('#usercentrics-root').shadowRoot.querySelector("button[data-testid='uc-accept-all-button']")""")
  element.click()
except NoSuchElementException:
  pass

This works for me with the website you have shared.

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 KunduK