为什么我无法使用selenium找到xpath?

问题描述 投票:0回答:1

https://www.auronia.de/trauring-konfigurator

如何点击cookie字段的接受按钮?不知怎的,我无法找到打开网站的xpath。

我得到了这个xpath:'//[@id =“focus-lock-id”]/div/div/div[2]/div/div/div[2]/div/div/button[2]'

我不断收到此错误消息:

发生错误:消息:没有这样的元素:无法定位元素:{“method”:“xpath”,“selector”:“//[@id =“focus-lock-id”]/div/div/div [2]/div/div/div[2]/div/div/按钮[2]"}

代码的相应部分如下所示:

try:
            if config.get("cookies_button") and cookies == 1:
                # cookies button if necessary to click
                time.sleep(10)
                print("looking for cookies button")
                button_cookies = driver.find_element(By.XPATH, config["cookies_button"])
                print("clicking cookies")
                WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.XPATH,                     button_cookies))).click()
                print("clicked the cookies button")
                cookies = 0
                time.sleep(2)  # Adjust as needed for the modal dialog to appear

“cookies_button”指的是上面显示的xpath,从错误消息中可以看到,它是同一个xpath。

但是为什么不起作用呢?我没有看到任何 iframe。不确定我在这里做错了什么?

selenium-webdriver xpath
1个回答
0
投票

问题是您要查找的元素位于影子根中,

<div id="usercentrics-root" data-created-at="1714251385660" style="">
  #shadow-root (open)

它的行为类似于 IFRAME。在查找元素之前,您必须将 Selenium 的上下文切换到该影子根中。下面是代码示例。

shadow_host = driver.find_element(By.ID, "usercentrics-root")
shadow_root = shadow_host.shadow_root
shadow_content = shadow_root.find_element(By.CSS_SELECTOR, "button[@data-testid='uc-accept-all-button']")
© www.soinside.com 2019 - 2024. All rights reserved.