From af130b2a0808ab6a49a5361447ecc230d7af665f Mon Sep 17 00:00:00 2001 From: JYunth Date: Mon, 16 Nov 2026 18:55:23 +0530 Subject: [PATCH] fix(core): escape text and attribute values in flatten_dom_to_str flatten_dom_to_str wrote text nodes and attribute values out as-is and then re-parsed the result with BeautifulSoup. Page text that looks like markup (e.g. a code sample) became real elements in the observation, a `"` inside an attribute value split it into bogus attributes, and CDATA content was mangled. Escape text and CDATA content with html.escape(quote=False) and attribute values with html.escape(). CDATA is now printed as escaped text, since the HTML parser used here doesn't support CDATA sections. Adds tests with an HTML page (text, attributes) and an XHTML page (CDATA). --- browsergym/core/src/browsergym/utils/obs.py | 11 ++-- tests/core/data/special_characters.html | 15 ++++++ tests/core/data/special_characters.xhtml | 9 ++++ tests/core/test_observation.py | 58 ++++++++++++++++++++- 4 files changed, 88 insertions(+), 5 deletions(-) create mode 100644 tests/core/data/special_characters.html create mode 100644 tests/core/data/special_characters.xhtml diff --git a/browsergym/core/src/browsergym/utils/obs.py b/browsergym/core/src/browsergym/utils/obs.py index db5b8ce03..a2e7ab378 100644 --- a/browsergym/core/src/browsergym/utils/obs.py +++ b/browsergym/core/src/browsergym/utils/obs.py @@ -1,4 +1,5 @@ import ast +import html as html_lib import logging import math import re @@ -77,14 +78,16 @@ def dfs(node_idx: int, parent_node_skipped: bool) -> str: skip_node = False # text nodes: print text content only if parent was not skipped + # (escaped, so that text which looks like markup is not parsed as markup) if node_type == 3: # node_name == "#text" if not parent_node_skipped and node_value is not None: - html_before += node_value + html_before += html_lib.escape(node_value, quote=False) - # CData nodes: print content only if parent was not skipped + # CData nodes: print content as escaped text only if parent was not skipped + # (the HTML parser used below does not support CDATA sections) elif node_type == 4: # node_name == "#cdata-section": if not parent_node_skipped and node_value is not None: - html_before += f"" + html_before += html_lib.escape(node_value, quote=False) # processing instructions, comments, documents, doctypes, document fragments: don't print elif node_type in (7, 8, 9, 10, 11): @@ -117,7 +120,7 @@ def dfs(node_idx: int, parent_node_skipped: bool) -> str: attributes.append(f"{attr_name}") else: # attribute value present - attributes.append(f'{attr_name}="{attr_value}"') + attributes.append(f'{attr_name}="{html_lib.escape(attr_value)}"') skip_node, extra_attributes_to_print = _process_bid( bid, diff --git a/tests/core/data/special_characters.html b/tests/core/data/special_characters.html new file mode 100644 index 000000000..88b10a409 --- /dev/null +++ b/tests/core/data/special_characters.html @@ -0,0 +1,15 @@ + + + + Special characters + + +

Write <button onclick="go()">Go</button> in the template.

+

Check that a < b && b > c.

+ + + + x < y && "z" > 1 + + + diff --git a/tests/core/data/special_characters.xhtml b/tests/core/data/special_characters.xhtml new file mode 100644 index 000000000..df3f2f884 --- /dev/null +++ b/tests/core/data/special_characters.xhtml @@ -0,0 +1,9 @@ + + + + Special characters (XHTML) + + +

1]]>

+ + diff --git a/tests/core/test_observation.py b/tests/core/test_observation.py index 36bb34193..29c65fe4b 100644 --- a/tests/core/test_observation.py +++ b/tests/core/test_observation.py @@ -19,7 +19,7 @@ extract_merged_axtree, extract_screenshot, ) -from browsergym.utils.obs import flatten_axtree_to_str, flatten_dom_to_str +from browsergym.utils.obs import flatten_axtree_to_str, flatten_dom_to_str, prune_html __SLOW_MO = 1000 if "DISPLAY_BROWSER" in os.environ else None __HEADLESS = False if "DISPLAY_BROWSER" in os.environ else True @@ -39,6 +39,8 @@ OUTER_IFRAME_URL = f"file://{__DATA_DIR}/basic_shadow_iframe_site/outer-iframe.html" CUSTOM_PAGE_URL = f"file://{__DATA_DIR}/custom_page/basic_iframe.html" MULTI_IFRAME_URL = f"file://{__DATA_DIR}/basic_iframe_site/basic_iframe_2.html" +SPECIAL_CHARS_URL = f"file://{__DATA_DIR}/special_characters.html" +SPECIAL_CHARS_XHTML_URL = f"file://{__DATA_DIR}/special_characters.xhtml" @pytest.mark.skip(reason="TODO: how to get the final viewport size right?") @@ -329,6 +331,60 @@ def test_dom_has_bids_no_aria(url): env.close() +def test_dom_to_text_special_characters(): + env = gym.make( + "browsergym/openended", + task_kwargs={"start_url": SPECIAL_CHARS_URL}, + headless=__HEADLESS, + slow_mo=__SLOW_MO, + timeout=__TIMEOUT, + ) + obs, info = env.reset() + + dom = flatten_dom_to_str(obs["dom_object"]) + for html in (dom, prune_html(dom)): + soup = bs4.BeautifulSoup(html, "lxml") + + # text that looks like markup stays text + p = soup.find(id="text-markup") + assert ( + p.get_text(" ", strip=True) + == 'Write in the template.' + ) + assert p.find("button") is None + + p = soup.find(id="text-symbols") + assert p.get_text(strip=True) == "Check that a < b && b > c." + + # attribute values keep their quotes and special characters + button = soup.find(id="attr-quotes") + assert button["title"] == 'Say "hi" & wave' + assert "hi" not in button.attrs and "wave" not in button.attrs + + textbox = soup.find(id="attr-markup") + assert textbox["placeholder"] == "bold & 'quoted'" + + env.close() + + +def test_dom_to_text_cdata(): + # CDATA sections only exist as DOM nodes in XML documents + env = gym.make( + "browsergym/openended", + task_kwargs={"start_url": SPECIAL_CHARS_XHTML_URL}, + headless=__HEADLESS, + slow_mo=__SLOW_MO, + timeout=__TIMEOUT, + ) + obs, info = env.reset() + + dom = flatten_dom_to_str(obs["dom_object"]) + soup = bs4.BeautifulSoup(dom, "lxml") + assert soup.find(id="cdata").get_text(strip=True) == 'x < y && "z" > 1' + + env.close() + + def test_dom_to_text(): env = gym.make( "browsergym/openended",