简体   繁体   English

如何单击 selenium-python 中的阴影框?

[英]How to click on the shadowbox in selenium-python?

I am trying to create an automation program.我正在尝试创建一个自动化程序。 I want to click on the "Accept Cookies" shadowbox on the given website.我想点击给定网站上的“接受 Cookie”影子框。 Here's how I have tried to achieve this:以下是我尝试实现这一目标的方法:

driver = webdriver.Chrome('chromedriver')
driver.get(r'https://www.studydrive.net/')

script = '''return document.querySelector('#usercentrics-root').shadowRoot.querySelector('button[aria-label="Accept All"]')'''
accept_all_btn = driver.execute_script(script)
accept_all_btn.click()

Here's the error that I get after following this approach:这是我在遵循这种方法后得到的错误:

AttributeError: 'NoneType' object has no attribute 'click'

I don't know, what I am doing wrong here.我不知道,我在这里做错了什么。 Any help is appreciated.任何帮助表示赞赏。 Thank you in advance.先感谢您。

wait=WebDriverWait(driver, 60)
driver.get("https://www.studydrive.net/")
elem = wait.until(EC.presence_of_element_located((By.ID,"usercentrics-root")))

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

Simply wait for the element and then proceed to click the accept all button.只需等待元素,然后继续单击全部接受按钮。 No aria-label was specified so I used another attribute.没有指定 aria-label,所以我使用了另一个属性。

Imports:进口:

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

The element Accept all button is within a #shadow-root (open)元素接受所有按钮位于#shadow-root(打开)

影子根


Solution解决方案

Tto click() on the desired element you need to use shadowRoot.querySelector() Tto click()你需要使用shadowRoot.querySelector()所需的元素

查询选择器

You can use the following Locator Strategy :您可以使用以下定位器策略

driver = webdriver.Chrome(service=s, options=options)
driver.get("https://www.studydrive.net/")
time.sleep(5)
accept_all = driver.execute_script('''return document.querySelector("#usercentrics-root").shadowRoot.querySelector("button[data-testid='uc-accept-all-button']")''')
accept_all.click()
        

PS: The cookie popup surfaces on the screen after significant amount of time, so you may have to induce some waits PS:屏幕上的 cookie 弹出窗口会在很长一段时间后出现,因此您可能需要进行一些等待


References参考

You can find a couple of relevant detailed discussions in:您可以在以下位置找到一些相关的详细讨论:

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

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