Access shadow root content with selenium

Question:

I’m trying to accept the cookie pop up on http://www.immobilienscout24.de.
I’m using selenium 4.61, webdriver-manger with chrome, python 3.11 and Fedora 37, but I’m always getting an error.

I’m using the following code

driver = webdriver.Chrome(ChromeDriverManager().install())

def accept_cookies():
    shadow_root = WebDriverWait(driver, 2).until(EC.presence_of_element_located((By.CSS_SELECTOR, "#usercentrics-root"))).shadow_root
    shadow_root.find_element((By.CLASS_NAME, "sc-gsDKAQ fWOgSr")).click()

url = 'http://www.immobilienscout24.de/'

driver.get(url)

time.sleep(10)

accept_cookies()

The sleeping is only done to have the cookie pop up loaded.
Error is: selenium.common.exceptions.InvalidArgumentException: Message: invalid argument: ‘using’ must be a string on shadow_root.find_element((By.CLASS_NAME, ‘sc-gsDKAQ fWOgSr’))

Asked By: PeterF5242

||

Answers:

The following code works for me:

url = "http://www.immobilienscout24.de/"
driver.get(url)

time.sleep(10)

element = driver.execute_script("""return document.querySelector('#usercentrics-root').shadowRoot.querySelector("button[data-testid='uc-accept-all-button']")""")
element.click()
Answered By: Prophet