0

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?

undetected Selenium
  • 183,867
  • 41
  • 278
  • 352
Jens Meier
  • 1
  • 1
  • 4

2 Answers2

0

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:

Benjamin Loison
  • 3,782
  • 4
  • 16
  • 33
undetected Selenium
  • 183,867
  • 41
  • 278
  • 352
  • Thank you very much. That worked for me. But why didn't my code work? Would it have worked with the ec visibility or something like that? – Jens Meier Dec 11 '21 at 11:02
  • When there is a [#shadow-root (open)](https://stackoverflow.com/questions/55761810/how-to-automate-shadow-dom-elements-using-selenium/55763793#55763793) you have to use `querySelector()`. Even [WebDriverWait](https://stackoverflow.com/questions/59130200/selenium-wait-until-element-is-present-visible-and-interactable/59130336#59130336) alone won't be able to do. – undetected Selenium Dec 11 '21 at 12:41
-1

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...)

Benjamin Loison
  • 3,782
  • 4
  • 16
  • 33
Pablo
  • 364
  • 1
  • 10