Best way to click a button within #shadow-root (open) via Python and Selenium

Question:

I am currently dabbling in Python in combination with Selenium. Here I came across the topic of Java Script buttons. I am looking for the smartest way to find out how to execute a Java-Script code (in this case a button) the easiest way.

My goals:

  1. Open web page http://www.easyCredit.de
  2. Accept the Cockies there
  3. Click the "Jetzt berechnen" button
  4. Click the "Zu den finanziellen Angaben" button

Number 1 and 2, I got right with a lot of research. Now it’s time to click the button. This can be identified quite well in the code, but still I do not succeed in clicking.

<input type="submit" class="calculator__submit-button" value="calculate now">

I have now tried it similar to the cockies, but unfortunately it does not work. I hope you can help me.

Here is my code:

from selenium import webdriver
from selenium.webdriver.common.by import By
import time

def expand_shadow_element(element):
  shadow_root = browser.execute_script('return arguments[0].shadowRoot', element)
  return shadow_root

# link to Chromedriver
browser = webdriver.Chrome('/usr/local/bin/chromedriver')

# maximize window
browser.maximize_window()

# URL
browser.get('https://www.easycredit.de/')

# wait
time.sleep(5)

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

# wait
time.sleep(5)

# click "Jetzt berechnen" 
berechnen_button = browser.execute_script("""return document.querySelector('rr-62f0ff69f069c').shadowRoot.querySelector("button[class='calculator__submit-button']")""")
berechnen_button.click()

The last part does not work.

This is the button I want to click:

enter image description here

Asked By: edstrinova

||

Answers:

The element Jetzt berechnen is within #shadow-root (open) and is an <input> element.

Jetzt


Solution

To click on Jetzt berechnen you can use the following line of code:

berechnen_button = browser.execute_script("""return document.querySelector('kredit-rechner').shadowRoot.querySelector('input.calculator__submit-button')""")
berechnen_button.click()
Answered By: undetected Selenium