无法使用 Playwright 访问 Shadow DOM 内部的文本。

huangapple go评论127阅读模式
英文:

Can not access text inside Shadow DOM using playwright

问题

我正在尝试使用 Playwright 来断言如下的文本,该文本位于没有与特定文本相关联的标签的 open shadow root 中。这些文本位于表格单元格内。

<div>
<table-cell>
  #shadow-root (open)
  "Text content"
</table-cell>

我试图断言 #shadow-root 中的 "Text content",它位于 shadow DOM 下面。我能够唯一地定位 <table-cell>,但无法获取其中的文本。无论我尝试使用哪种方法来检索文本,它总是返回一个空字符串或对象。以下是我尝试的 TypeScript 代码示例:

const text = this.page.locator('table-cell').innerText();

我能够获取其他位于具有与文本相关的标签的 shadow root 内的文本。但在这种情况下,这个特定的文本行没有与其相关联的任何标签,因此这些方法无法像其他情况那样工作。

如何获取仅包含文本而不包含任何标签的 #shadow-root 内容?

英文:

I am trying to use playwright to assert text like below which is inside open shadow root which has no tags associated to that specific text. These texts are inside table cells.

&lt;div&gt;
&lt;table-cell&gt;
  #shadow-root (open)
  &quot;Text content&quot;
&lt;/table-cell&gt;

I am trying to assert "Text content" which is under shadow DOM. I was able to uniquely locate <table-cell> but can not get the text inside it. It always return an empty string or object depends on the method I tried to retrieve the text. Example typescript code I tried is below,

const text = this.page.locator(&#39;table-cell&#39;).innerText();

I was able to get other texts which are inside shadow root which has a tag associated with that text. But in this case this specific text line don't have any tag associated to that so the methods aren't working as for other scenarios.

How do I get the contents of #shadow-root if it only contains the text, without any tags ?

答案1

得分: 1

"innerText" 是在 "HTMLElement" 上的一个属性

一个 shadowRoot 不是一个 "HTMLElement",并且没有 "innerText" 属性。

它确实有一个 "innerHTML" 属性:https://developer.mozilla.org/en-US/docs/Web/API/ShadowRoot

let text = document.querySelector(&quot;your-element&quot;).shadowRoot.innerHTML

获取到的文本

英文:

innerText is a property on HTMLElement

A shadowRoot is not a HTMLElement and does not have an innerText property.

It does have a innerHTML property: https://developer.mozilla.org/en-US/docs/Web/API/ShadowRoot

let text = document.querySelector(&quot;your-element&quot;).shadowRoot.innerHTML

Gets you the text

huangapple
  • 本文由 发表于 2023年7月10日 12:44:37
  • 转载请务必保留本文链接:https://go.coder-hub.com/76650720.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定