Unable to locate parent of shadowded DOM element on https://www.bahn.de

13 views Asked by At

I generated a python export from selenium IDE which works well to navigate through the website, but fails to bypass the consent dialog.

Here's what selenium IDE is recording:

import pytest
import time
import json
import pytest
import time
import json
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.support import expected_conditions
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.desired_capabilities import DesiredCapabilities

class TestBahndeConsentDialog():
  def __init__(self):
    self.driver = webdriver.Chrome()
    self.vars = {}
  
  def teardown_method(self, method):
    self.driver.quit()
  
  def test_bahndeConsentDialog(self):
    # Test name: Bahn.de - Consent Dialog
    # Step # | name | target | value
    # 1 | open | / | 
    self.driver.get("https://www.bahn.de/")
    # 2 | setWindowSize | 1265x1040 | 
    self.driver.set_window_size(1265, 1040)
    # 3 | click | css=body > div:nth-child(1) | 
    self.driver.find_element(By.CSS_SELECTOR, "body > div:nth-child(1)").click()

run = TestBahndeConsentDialog()
#try:
run.test_bahndeConsentDialog()
#finally:
run.driver.quit()

Running this code will bring up this error: selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {"method":"css selector","selector":"body > div:nth-child(1)"}

Investigating the button with Chrome's inspector, the button seems not accessible as it is shadowed: html snippet of #shadow-root

Suggestions in related post https://stackoverflow.com/questions/76086069/selenium-webdriver-click-on-accept-cookies-button indicate to access a parent HTML element first to apply the *.click() function on the button itself:

shadow = driver.find_element(By.TAG_NAME, "dock-privacy-settings").shadow_root
shadow.find_element(By.ID,"save-all-modal-dialog").click()

Unfortunately in case of bahn.de the #shadow-root part is inside a nameless element where I have no clue on how to locate this element. From my understanding using the "querySelector" approach requires to specify the name for the targeted HTML element as mentioned in this posts: https://stackoverflow.com/questions/72584474/unable-to-locate-accept-button-selenium-beginner-web-scraping

How can I locate the correct nameless element in my case?

0

There are 0 answers