> For the complete documentation index, see [llms.txt](https://help.autify.com/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://help.autify.com/nocode-web/when-the-test-doesnt-work/test-issues/how-to-grab-an-element-with-dynamic-data.md). Agents can also search and read this documentation through its [MCP server](https://help.autify.com/~gitbook/mcp).

# 要素が動的なデータを含む場合、どうすればテストを安定させられますか？

ターゲット要素に、シナリオ記録時と異なるデータ/テキストがある場合の、「対象要素が見つかりませんでした」エラーのトラブルシューティングガイドです。

このページでは、動的なデータに対してテストの実行を安定させる方法を紹介します。

## 原因

テスト実行時、テスト実行エンジンは要素の内部のテキストを見て、その要素が記録されたものと同じかどうかを確認します。 要素の同一性は、その中のテキストやデータだけで決まるわけではありませんが、日付、名前、メールアドレスなどの動的なデータは、「対象要素が見つかりませんでした」エラーを引き起こす可能性があります。

## 解決方法

### 1. CSSセレクターを使用する

CSSのセレクターを使用するのが、最も手っ取り早い対処法です。 例を見てみましょう。 下のスクリーンショットでは、最新記事がページの上半分に表示されているのがわかります。新しい記事が作成されると、タイトル、日付、著者が変わり、古い記事はページの下半分にあるカードのようなリストに移動されます。

![](https://50135409-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fof7cb8AGXhWvWThq3R0w%2Fuploads%2Fgit-blob-d8eccc95e54db919701e81c65012527a614df165%2Fnewest-title.png?alt=media)

最新記事のタイトルがクリックされたことを確認するために、このように指定します。

```
div.LatestPost h1
```

![](https://50135409-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fof7cb8AGXhWvWThq3R0w%2Fuploads%2Fgit-blob-2a60872c7441c519e4b9818579407792f5cee099%2Fdynamic-data-css-selector-example.png?alt=media)

(CSSのセレクターの基本を学ぶには、[CSSセレクターを使いこなす](https://help.autify.com/nocode-web/autify-university/advanced/locator-feature/how-to-use-css-selectors-effectively.md)をご覧ください。)

## 2. ウェブサイトの構造を更新する

テスト実行エンジンは、HTMLの情報を使って要素を識別しています。 各要素をよりユニークにすることで、テストをより安定させることができます。 最も一般的な修正は、`span`, `div` などの汎用的な要素を、より意味のあるもの（専門用語で「セマンティック」）に置き換えることです。

#### ❌ 手がかりの少ないHTML構造

```html
<div>
    <div>
        <div class="bold big">This is the page title</div>
        <div>
            Date: <span class="gray small">Jan 1, 2021</span>
        </div>
        <div>John</div>
    </div>
</div>
```

#### ✅ より多くの手がかりを持つHTML構造

```html
<main>
    <article>
        <h1>This is the page title</h1>
        <p id="posted-at" aria-label="date" >
            Date: <time datetime="2021-01-01">Jan 1, 2021</time>
        </p>
        <p id="written-by" aria-label="author">John</p>
    </article>
</main>
```

最初の例のブログページに戻ると、新しい記事が出てきてもCSSセレクターを使わずに最新記事のタイトルを取得することができます。 最新記事のタイトルは `h1` で、つまりページのトップレベルのヘッダーであるのに対し、古い記事のタイトルは `h3` です。テスト実行エンジンはこの違いを利用して、どのタイトルが最新の記事のものかを区別することができます。

![](https://50135409-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fof7cb8AGXhWvWThq3R0w%2Fuploads%2Fgit-blob-f447347d8ec46d1271f17ddac47a49edacb7670b%2Fno-css-selector.png?alt=media)

ウェブサイトの構造を改良して、より意味のあるものにすることは、低コストでできることではないかもしれません。しかし、特に効果的なCSSセレクターが見つからない場合は、試してみる価値があります。

### JSステップを使用する

以下のように、期待されるテキストを持つ要素にクエリを発行することができます。

```javascript
const expectedText = "Dec 15, 2021";
const allSpanElementsInPage = document.querySelectorAll("span");

// You need to convert the NodeList returned by querySelector to an Array
// to use the filter method.
const filteredElements = Array.from(allSpanElementsInPage).filter(
    (el) => {
        return el.innerText === expectedText;
    }
);

if (filteredElements.length === 1) {
    // Perform action as needed. For example, clicking.
    filteredElements[0].click();
} else if (filteredElements.length === 0) {
   throw new Error("No elements found with JS")
} else {
   throw new Error(`Could not determine single element. ${filteredElements.length} found.`)
}
```

## 関連記事

* CSS セレクターの基本については、[CSSセレクターを使いこなす](https://help.autify.com/nocode-web/autify-university/advanced/locator-feature/how-to-use-css-selectors-effectively.md) をご覧ください。
* セマンティックの定義については、 [MDN Web Docs Glossary - Semantics](https://developer.mozilla.org/en-US/docs/Glossary/Semantics) を参照してください。


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation by asking a question.

Perform an HTTP GET request on the following URL with the `ask` and `goal` query parameters:

```
GET https://help.autify.com/nocode-web/when-the-test-doesnt-work/test-issues/how-to-grab-an-element-with-dynamic-data.md?ask=<question>&goal=<user_goal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is what the user is ultimately trying to achieve, the reason they need the answer. Sharing it helps GitBook give you a better, more relevant answer. A goal is most helpful when it describes the outcome the user wants rather than restating the question. For example, with `ask=how do I create an API token`, a goal like `automate deployments from our CI pipeline` lets GitBook tailor the answer to that use case.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
