Selenium如何获取Shadow DOM下的元素属性?
时间: 2024-12-19 07:29:06 浏览: 191
在Selenium中,获取Shadow DOM下的元素属性通常涉及到两步:首先找到元素,然后访问它的属性。由于Shadow DOM元素默认是不可见的(对于非JavaScript开发者),所以我们需要用JavaScript脚本来获取其内容。
下面是一个示例,展示如何通过Selenium的execute_script
函数获取Shadow DOM元素的属性:
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.support import expected_conditions as EC
# 确保页面加载完成并找到了元素
element = WebDriverWait(driver, 10).until(
EC.presence_of_element_located((By.CSS_SELECTOR, '[shadow-host]')) # shadow-host是你期望找到实际Shadow DOM元素的父元素的选择器
)
# 获取Shadow DOM元素,传递给JavaScript上下文
shadow_root = driver.execute_script("return arguments[0].shadowRoot;", element)
# 现在可以在Shadow DOM中查找你需要的属性,比如一个属性名为'text'的元素
property_value = driver.execute_script("""
const elem = arguments[0];
return elem.querySelector('path[text]').getAttribute('text');
""", shadow_root)
print(f"Element attribute value is: {property_value}")
在这个例子中,我们首先找到包含Shadow DOM的元素,然后通过shadowRoot
属性获取Shadow DOM。接着在Shadow DOM内执行JavaScript代码来获取特定属性的值。
相关推荐


















