繁体   English   中英

Selenium - 无法在 cookie 弹出窗口中找到按钮

[英]Selenium - unable to locate button on cookie popup

我正在尝试使用 selenium 解析该网站,但我找不到我需要确认才能继续的 cookie 弹出窗口的按钮。 我知道我首先需要加载页面,然后等待 cookie 弹出窗口出现,尽管这应该由睡眠函数很好地处理。

弹出窗口中按钮的 html 看起来像这样(通过 firefox F12 检索)。 我试图简单地单击“确定”按钮:

<button role="button" data-testid="uc-customize-button" style="border: 1px solid rgb(0, 139, 2);" class="sc-gsDKAQ hWcdhQ">Einstellungen oder ablehnen</button>
<div class="sc-bBHxTw foBPAO"></div>
<button role="button" data-testid="uc-accept-all-button" style="border: 1px solid rgb(0, 139, 2);" class="sc-gsDKAQ fILFKg">OK</button>

我试图通过“确定”按钮的 xpath 简单地找到按钮:

from time import sleep
from selenium import webdriver
from selenium.webdriver.common.by import By

# adapting: https://stackoverflow.com/questions/64032271/handling-accept-cookies-popup-with-selenium-in-python

BASE_URL = "https://www.immowelt.at/suche/wohnungen/mieten"

driver = webdriver.Firefox()
driver.get(BASE_URL)
sleep(10)

# cannot locate by XPATH
driver.find_element(
    By.XPATH, "/div/div/div[2]/div/div[2]/div/div/div/button[2]"
).click()

# weird thing is, I also cannot retrieve any of the buttons (although I know they exist)
buttons = driver.find_elements(By.TAG_NAME, "button")

任何想法为什么我找不到按钮?

通过检查 HTML,我们可以看到该按钮位于影子根内。

在此处输入图像描述

因此,为了能够与按钮交互,我们必须首先选择影子根的父级,即id=usercentrics-rootdiv元素,然后我们可以选择按钮并单击它:

driver.execute_script('''return document.querySelector("#usercentrics-root").shadowRoot.querySelector("button[data-testid='uc-accept-all-button']")''').click()

或者,更易读的代码:

shadow_parent = driver.find_element(By.CSS_SELECTOR, '#usercentrics-root')
outer = driver.execute_script('return arguments[0].shadowRoot', shadow_parent)
outer.find_element(By.CSS_SELECTOR, "button[data-testid='uc-accept-all-button']").click()

暂无
暂无

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

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