繁体   English   中英

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

[英]Python Selenium can't find element by xpath within #shadow-root (open) using Selenium and Python

我正在浏览这个网站: https://www.aldi-onlineshop.de/p/multimedia-pc-s23004-md34655-1014700/我尝试使用以下脚本单击按钮:“Alle bestätigen”:

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

但这不起作用,它收到了错误:

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

我怎样才能解决这个问题,所以它找到了元素?

您的 xpath 可能不正确,我建议您将 go 逐步降低一个级别,例如:

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

如果正确:

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

...

我注意到的另一件事是,是否需要双“//”? ('/html/body/div[4]//div...)

元素Alle bestätigen按钮位于#shadow-root(打开)

阿尔迪


解决方案

要在所需元素上单击() ,您需要使用querySelector()并且可以使用以下定位器策略

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

参考

您可以在以下位置找到一些相关的详细讨论:

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM