Home > Blockchain >  How to click on the shadowbox in selenium-python?
How to click on the shadowbox in selenium-python?

Time:12-01

I am trying to create an automation program. I want to click on the "Accept Cookies" shadowbox on the given website. Here's how I have tried to achieve this:

driver = webdriver.Chrome('chromedriver')
driver.get(r'https://www.studydrive.net/')

script = '''return document.querySelector('#usercentrics-root').shadowRoot.querySelector('button[aria-label="Accept All"]')'''
accept_all_btn = driver.execute_script(script)
accept_all_btn.click()

Here's the error that I get after following this approach:

AttributeError: 'NoneType' object has no attribute 'click'

I don't know, what I am doing wrong here. Any help is appreciated. Thank you in advance.

CodePudding user response:

wait=WebDriverWait(driver, 60)
driver.get("https://www.studydrive.net/")
elem = wait.until(EC.presence_of_element_located((By.ID,"usercentrics-root")))

script = '''return document.querySelector('#usercentrics-root').shadowRoot.querySelector('button[data-testid="uc-accept-all-button"]')'''
accept_all_btn = driver.execute_script(script)
accept_all_btn.click()

Simply wait for the element and then proceed to click the accept all button. No aria-label was specified so I used another attribute.

Imports:

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

CodePudding user response:

The element Accept all button is within a shadow-root


Solution

Tto click() on the desired element you need to use shadowRoot.querySelector()

querySelector

You can use the following Locator Strategy:

driver = webdriver.Chrome(service=s, options=options)
driver.get("https://www.studydrive.net/")
time.sleep(5)
accept_all = driver.execute_script('''return document.querySelector("#usercentrics-root").shadowRoot.querySelector("button[data-testid='uc-accept-all-button']")''')
accept_all.click()
        

PS: The cookie popup surfaces on the screen after significant amount of time, so you may have to induce some waits


References

You can find a couple of relevant detailed discussions in:

  • Related