Home > Net >  Python Selenium can't find element by xpath within #shadow-root (open) using Selenium and Pytho
Python Selenium can't find element by xpath within #shadow-root (open) using Selenium and Pytho

Time:12-11

I was browsing on this website: https://www.aldi-onlineshop.de/p/multimedia-pc-s23004-md34655-1014700/ I tried to click the button: "Alle bestätigen" with the following script:

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

driver = webdriver.Chrome()
driver.get("https://www.aldi-onlineshop.de/p/multimedia-pc-s23004-md34655-1014700/")
agree = driver.find_element_by_xpath('/html/body/div[4]//div/div/div/div/div/div[2]/div/div/div/div[1]/button')
agree.click()

But that didn't work and it received the error:

no such element: Unable to locate element: {"method":"xpath","selector":"/html/body/div[4]//div/div/div/div/div/div[2]/div/div/div/div[1]/button"}
(Session info: chrome=96.0.....)

How can I solve that problem, so it finds the element?

CodePudding user response:

The element Alle bestätigen button is within #shadow-root (open)

aldi


Solution

To click() on the desired element you need to use querySelector() and you can use the following Locator Strategy:

driver.get("https://www.aldi-onlineshop.de/p/multimedia-pc-s23004-md34655-1014700/")
time.sleep(5)
driver.execute_script('''return document.querySelector('div#usercentrics-root').shadowRoot.querySelector('button[data-testid="uc-accept-all-button"]')''').click()
        

References

You can find a couple of relevant detailed discussions in:

CodePudding user response:

Your xpath is possibly incorrect, I recommend that you go down a level step by step, for example:

 agree = driver.find_element_by_xpath('/html/body/div[4]/)

If its correct:

 agree = driver.find_element_by_xpath('/html/body/div[4]/div/)

...

Another thing I noticed, is that double "//" wanted? ('/html/body/div[4]//div...)

  • Related