Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 7 additions & 4 deletions browsergym/core/src/browsergym/utils/obs.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import ast
import html as html_lib
import logging
import math
import re
Expand Down Expand Up @@ -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"<!CDATA[[{node_value}]]>"
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):
Expand Down Expand Up @@ -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,
Expand Down
15 changes: 15 additions & 0 deletions tests/core/data/special_characters.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
<!DOCTYPE html>
<html>
<head>
<title>Special characters</title>
</head>
<body>
<p id="text-markup">Write &lt;button onclick="go()"&gt;Go&lt;/button&gt; in the template.</p>
<p id="text-symbols">Check that a &lt; b &amp;&amp; b &gt; c.</p>
<button id="attr-quotes" title='Say "hi" &amp; wave'>Greet</button>
<input id="attr-markup" type="text" placeholder="&lt;b&gt;bold&lt;/b&gt; &amp; 'quoted'">
<svg width="200" height="40">
<text x="0" y="20"><![CDATA[x < y && "z" > 1]]></text>
</svg>
</body>
</html>
9 changes: 9 additions & 0 deletions tests/core/data/special_characters.xhtml
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
<?xml version="1.0" encoding="UTF-8"?>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Special characters (XHTML)</title>
</head>
<body>
<p id="cdata"><![CDATA[x < y && "z" > 1]]></p>
</body>
</html>
58 changes: 57 additions & 1 deletion tests/core/test_observation.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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?")
Expand Down Expand Up @@ -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 <button onclick="go()">Go</button> 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"] == "<b>bold</b> & '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",
Expand Down