At AcmeQA, automated UI tests fail because element IDs change on every page load. Implement a function that finds the best matching element using stable properties instead of relying on the full id value.
Given a list of element records and a target specification, return the index of the first element that matches all required stable fields. A field matches if:
tag must match exactly when provided.text must match exactly when provided.attributes must exist in the element's attributes.id_prefix is provided, the element's id must start with that prefix.If no element matches, return -1.
elements is a list of dictionaries. Each element has keys: tag (string), id (string), text (string), and attributes (dictionary of strings).target is a dictionary with optional keys: tag, text, id_prefix, and attributes.-1.Example 1
Input: elements = [{"tag":"button","id":"login_4831","text":"Login","attributes":{"data-testid":"login-btn","role":"primary"}}], target = {"tag":"button","text":"Login","attributes":{"data-testid":"login-btn"},"id_prefix":"login_"}
Output: 0
Explanation: The button matches the tag, text, required attribute, and its ID starts with login_.
Example 2
Input: elements = [{"tag":"input","id":"user_91","text":"","attributes":{"name":"email"}}], target = {"tag":"input","attributes":{"name":"password"}}
Output: -1
Explanation: The required attribute does not match.
1 <= len(elements) <= 10^4attributes dictionary contains at most 20 key-value pairselements = [{"tag":"button","id":"login_4831","text":"Login","attributes":{"data-testid":"login-btn","role":"primary"}}], target = {"tag":"button","text":"Login","attributes":{"data-testid":"login-btn"},"id_prefix":"login_"}Output0WhyThe only element satisfies every required condition, so its index is returned.elements = [{"tag":"input","id":"user_91","text":"","attributes":{"name":"email"}}], target = {"tag":"input","attributes":{"name":"password"}}Output-1WhyThe element has the correct tag, but the required attribute value does not match.elements = [{"tag":"button","id":"save_1","text":"Save","attributes":{"data-testid":"save-btn"}}, {"tag":"button","id":"save_2","text":"Save","attributes":{"data-testid":"save-btn"}}], target = {"tag":"button","text":"Save","attributes":{"data-testid":"save-btn"}}Output0WhyBoth elements match, so the first matching index is returned.1 <= len(elements) <= 10^4Each element contains keys `tag`, `id`, `text`, and `attributes`0 <= len(attributes) <= 20 for each elementAll attribute keys and values are stringsTarget may include any subset of: `tag`, `text`, `id_prefix`, `attributes`def find_stable_element(elements, target):