最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

python - Try to click on element in shadow root? - Stack Overflow

programmeradmin3浏览0评论

i try to click on a button in a shadow root using the following code:

from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdrivermon.by import By
import time


print(f"Checking Browser driver...")
options = Options()
# options.add_argument('--headless=new')  
options.add_argument("start-maximized")
options.add_argument('--log-level=3')  
options.add_experimental_option("prefs", {"profile.default_content_setting_values.notifications": 1})    
options.add_experimental_option("excludeSwitches", ["enable-automation"])
options.add_experimental_option('excludeSwitches', ['enable-logging'])
options.add_experimental_option('useAutomationExtension', False)
options.add_argument('--disable-blink-features=AutomationControlled') 
srv=Service()
driver = webdriver.Chrome (service=srv, options=options)    
waitWD = WebDriverWait (driver, 10)         

link = "="
driver.get (link)     
time.sleep(5)
shadowHost = driver.find_element(By.XPATH,'//div[@class="szn-cmp-dialog-container"]')
shadowRoot = shadowHost.shadow_root
time.sleep(5)
shadowRoot.find_element(By.XPATH, '//button[@data-testid="cw-button-agree-with-ads"]').click()      
input("Press!")

But i get the following error:

(selenium) C:\DEVNEU\Fiverr2025\TRY\readingmadness>python test.py
Checking Browser driver...
Traceback (most recent call last):
  File "C:\DEVNEU\Fiverr2025\TRY\readingmadness\test.py", line 29, in <module>
    shadowRoot.find_element(By.XPATH, '//button[@data-testid="cw-button-agree-with-ads"]').click()
    ~~~~~~~~~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\DEVNEU\.venv\selenium\Lib\site-packages\selenium\webdriver\remote\shadowroot.py", line 53, in find_element
    return self._execute(Command.FIND_ELEMENT_FROM_SHADOW_ROOT, {"using": by, "value": value})["value"]
           ~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\DEVNEU\.venv\selenium\Lib\site-packages\selenium\webdriver\remote\shadowroot.py", line 82, in _execute
    return self.session.execute(command, params)
           ~~~~~~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^
  File "C:\DEVNEU\.venv\selenium\Lib\site-packages\selenium\webdriver\remote\webdriver.py", line 384, in execute
    self.error_handler.check_response(response)
    ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~^^^^^^^^^^
  File "C:\DEVNEU\.venv\selenium\Lib\site-packages\selenium\webdriver\remote\errorhandler.py", line 232, in check_response
    raise exception_class(message, screen, stacktrace)
seleniummon.exceptions.InvalidArgumentException: Message: invalid argument: invalid locator
  (Session info: chrome=133.0.6943.60)
Stacktrace:
        GetHandleVerifier [0x00007FF64EE46F15+28773]
        (No symbol) [0x00007FF64EDB2600]
        (No symbol) [0x00007FF64EC48FAA]
        (No symbol) [0x00007FF64EC9F05A]
        (No symbol) [0x00007FF64EC9F4FC]
        (No symbol) [0x00007FF64EC91CAC]
        (No symbol) [0x00007FF64ECC728F]
        (No symbol) [0x00007FF64EC91B36]
        (No symbol) [0x00007FF64ECC7460]
        (No symbol) [0x00007FF64ECEF6F3]
        (No symbol) [0x00007FF64ECC7023]
        (No symbol) [0x00007FF64EC8FF5E]
        (No symbol) [0x00007FF64EC911E3]
        GetHandleVerifier [0x00007FF64F19425D+3490733]
        GetHandleVerifier [0x00007FF64F1ABA43+3586963]
        GetHandleVerifier [0x00007FF64F1A147D+3544525]
        GetHandleVerifier [0x00007FF64EF0C9DA+838442]
        (No symbol) [0x00007FF64EDBD04F]
        (No symbol) [0x00007FF64EDB9614]
        (No symbol) [0x00007FF64EDB97B6]
        (No symbol) [0x00007FF64EDA8CE9]
        BaseThreadInitThunk [0x00007FFC4B4D259D+29]
    RtlUserThreadStart [0x00007FFC4C7AAF38+40]

How can i click the button in the shadow root?

i try to click on a button in a shadow root using the following code:

from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdrivermon.by import By
import time


print(f"Checking Browser driver...")
options = Options()
# options.add_argument('--headless=new')  
options.add_argument("start-maximized")
options.add_argument('--log-level=3')  
options.add_experimental_option("prefs", {"profile.default_content_setting_values.notifications": 1})    
options.add_experimental_option("excludeSwitches", ["enable-automation"])
options.add_experimental_option('excludeSwitches', ['enable-logging'])
options.add_experimental_option('useAutomationExtension', False)
options.add_argument('--disable-blink-features=AutomationControlled') 
srv=Service()
driver = webdriver.Chrome (service=srv, options=options)    
waitWD = WebDriverWait (driver, 10)         

link = "https://www.firmy.cz/kraj-liberecky/liberec/1818-liberec?q="
driver.get (link)     
time.sleep(5)
shadowHost = driver.find_element(By.XPATH,'//div[@class="szn-cmp-dialog-container"]')
shadowRoot = shadowHost.shadow_root
time.sleep(5)
shadowRoot.find_element(By.XPATH, '//button[@data-testid="cw-button-agree-with-ads"]').click()      
input("Press!")

But i get the following error:

(selenium) C:\DEVNEU\Fiverr2025\TRY\readingmadness>python test.py
Checking Browser driver...
Traceback (most recent call last):
  File "C:\DEVNEU\Fiverr2025\TRY\readingmadness\test.py", line 29, in <module>
    shadowRoot.find_element(By.XPATH, '//button[@data-testid="cw-button-agree-with-ads"]').click()
    ~~~~~~~~~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\DEVNEU\.venv\selenium\Lib\site-packages\selenium\webdriver\remote\shadowroot.py", line 53, in find_element
    return self._execute(Command.FIND_ELEMENT_FROM_SHADOW_ROOT, {"using": by, "value": value})["value"]
           ~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\DEVNEU\.venv\selenium\Lib\site-packages\selenium\webdriver\remote\shadowroot.py", line 82, in _execute
    return self.session.execute(command, params)
           ~~~~~~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^
  File "C:\DEVNEU\.venv\selenium\Lib\site-packages\selenium\webdriver\remote\webdriver.py", line 384, in execute
    self.error_handler.check_response(response)
    ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~^^^^^^^^^^
  File "C:\DEVNEU\.venv\selenium\Lib\site-packages\selenium\webdriver\remote\errorhandler.py", line 232, in check_response
    raise exception_class(message, screen, stacktrace)
seleniummon.exceptions.InvalidArgumentException: Message: invalid argument: invalid locator
  (Session info: chrome=133.0.6943.60)
Stacktrace:
        GetHandleVerifier [0x00007FF64EE46F15+28773]
        (No symbol) [0x00007FF64EDB2600]
        (No symbol) [0x00007FF64EC48FAA]
        (No symbol) [0x00007FF64EC9F05A]
        (No symbol) [0x00007FF64EC9F4FC]
        (No symbol) [0x00007FF64EC91CAC]
        (No symbol) [0x00007FF64ECC728F]
        (No symbol) [0x00007FF64EC91B36]
        (No symbol) [0x00007FF64ECC7460]
        (No symbol) [0x00007FF64ECEF6F3]
        (No symbol) [0x00007FF64ECC7023]
        (No symbol) [0x00007FF64EC8FF5E]
        (No symbol) [0x00007FF64EC911E3]
        GetHandleVerifier [0x00007FF64F19425D+3490733]
        GetHandleVerifier [0x00007FF64F1ABA43+3586963]
        GetHandleVerifier [0x00007FF64F1A147D+3544525]
        GetHandleVerifier [0x00007FF64EF0C9DA+838442]
        (No symbol) [0x00007FF64EDBD04F]
        (No symbol) [0x00007FF64EDB9614]
        (No symbol) [0x00007FF64EDB97B6]
        (No symbol) [0x00007FF64EDA8CE9]
        BaseThreadInitThunk [0x00007FFC4B4D259D+29]
    RtlUserThreadStart [0x00007FFC4C7AAF38+40]

How can i click the button in the shadow root?

Share Improve this question asked Feb 15 at 15:01 Rapid1898Rapid1898 1,2082 gold badges15 silver badges46 bronze badges 2
  • I see you are using xpath inside the shadow DOM, It is advisable to use CSS selector to access elements inside the shadow DOM structure. – Venkat Sai Commented Feb 15 at 16:57
  • Thanks a lot i think this solved my problem when i use this shadowRoot.find_element(By.CSS_SELECTOR, 'button[data-testid="cw-button-agree-with-ads"]').click() it seem to work (write this as an answer and i will accept it) – Rapid1898 Commented Feb 15 at 17:04
Add a comment  | 

1 Answer 1

Reset to default 0

Shadow DOM generally encapsulates the inner elements to be independent of the outer DOM structure. In other words, Shadow DOM creates an isolation branch of the tags from the main Document tree. Since XPath traverses through the main DOM tree it becomes difficult to access the elements inside the Shadow DOM. So it is always advisable to use CSS selectors instead of XPath when accessing elements inside a Shadow DOM since CSS operates in a local context.

Try to use the CSS selector and replace the last line of code with

shadowRoot.find_element(By.CSS_SELECTOR, 'button[data-testid="cw-button-agree-with-ads"]').click()

Hope this helps!

发布评论

评论列表(0)

  1. 暂无评论