在 Shadow DOM 中定位
相关学习资料: study.163.com/course/intr…
1、什么是Shadow DOM? Shadow DOM 是 Web Components 技术的一部分,它提供了一种将 HTML 结构、样式和行为封装在一个独立的、封闭的 DOM 中的机制。以下是一个使用 Shadow DOM 的例子,该例子展示了如何创建一个简单的自定义组件,并将内容、样式封装在 Shadow DOM 中。示例代码:
`
Shadow DOM Example /* 外部样式,不会影响 Shadow DOM 内部 */ .container { font-size: 20px; color: red; }<script>
// 自定义元素定义及 Shadow DOM 创建
class MyCustomElement extends HTMLElement {
constructor() {
super();
// 创建 Shadow Root
const shadowRoot = this.attachShadow({ mode: 'open' });
// Shadow DOM 内部样式和内容
shadowRoot.innerHTML = `
<style>
.shadow-content {
font-size: 16px;
color: blue;
}
</style>
<div class="shadow-content">This is inside the Shadow DOM.</div>
`;
}
}
// 注册自定义元素
customElements.define('my-custom-element', MyCustomElement);
// 将自定义元素添加到文档中
const customElement = document.createElement('my-custom-element');
document.body.appendChild(customElement);
// 注意:在实际应用中,你可能会将自定义元素直接写在 HTML 中,如:<my-custom-element></my-custom-element>
// 而不是通过 JavaScript 动态创建和添加。
</script>
`
2、如何查看Shadow DOM
首先打开浏览器控制台的设置选项
然后再找到Preference -> Elements,把show user anent shadow dom勾上
这时候我们再来看一下此时的dom元素发生了什么变化
我们会发现这些标签内部都大有乾坤,在这些标签下面都多了一个shadow root,在它里面才是这些标签的真实布局。
3、在 Shadow DOM 中定位 默认情况下,Playwright 中的所有定位器都使用 Shadow DOM 中的元素。例外情况包括:
通过 XPath 定位不会刺穿阴影根
不支持闭合模式阴影根
要定位,使用page.get_by_text("")或page.locator("", has_text="")都可以,要确保
包含文本“This is inside the Shadow DOM.”,示例代码如下:
page.goto("http://localhost:8080/shadowDOM.html") expect(page.get_by_text("This is inside the Shadow DOM.")).to_contain_text("Shadow DOM") expect(page.locator("div", has_text="This is inside the Shadow DOM.")).to_contain_text("This is inside")
相关学习资料: study.163.com/course/intr…