Skip to content

The headless browser for AI agents and web scraping

Bound markdown traversal and reuse table cell conversions

SGavrl1ee3ac12e25e
diff --git a/crates/obscura-js/src/markdown.rs b/crates/obscura-js/src/markdown.rs
index 7f008195..2aadbb33 100644
--- a/crates/obscura-js/src/markdown.rs
+++ b/crates/obscura-js/src/markdown.rs
@@ -1,20 +1,45 @@
//! Shared markdown extraction script used by the LP.getMarkdown CDP method
-//! and the CLI `--dump markdown` mode. Lives in obscura-browser so both
+//! and the CLI `--dump markdown` mode. Lives in obscura-js so both
//! obscura-cdp and obscura-cli can call it without depending on each other.
/// JS expression that walks `document.body` and returns a markdown string.
/// Must be evaluated against a Page that has a fully-bootstrapped JS runtime.
pub const HTML_TO_MARKDOWN_JS: &str = r#"
(function() {
- function toMd(el, depth) {
+ function toMd(el, depth, children, cells) {
if (!el) return '';
- var out = '';
if (el.nodeType === 3) return el.textContent || '';
if (el.nodeType !== 1) return '';
+ // Keep ordinary pages on the recursive fast path, with a bounded stack.
+ if (depth === 128) {
+ var stack = [{ node: el, kids: el.childNodes || [], index: 0, children: '', cells: [] }];
+ while (stack.length) {
+ var frame = stack[stack.length - 1];
+ if (frame.index < frame.kids.length) {
+ var child = frame.kids[frame.index++];
+ if (child.nodeType === 3) frame.children += child.textContent || '';
+ else if (child.nodeType === 1) stack.push({ node: child, kids: child.childNodes || [], index: 0, children: '', cells: [] });
+ continue;
+ }
+ var out = toMd(frame.node, -1, frame.children, frame.cells);
+ stack.pop();
+ if (!stack.length) return out;
+ var parent = stack[stack.length - 1];
+ parent.children += out;
+ parent.cells.push(out);
+ }
+ }
var tag = (el.tagName || '').toLowerCase();
- var children = '';
- var cn = el.childNodes || [];
- for (var i = 0; i < cn.length; i++) children += toMd(cn[i], depth);
+ if (depth !== -1) {
+ children = '';
+ cells = tag === 'tr' ? [] : null;
+ var cn = el.childNodes || [];
+ for (var i = 0; i < cn.length; i++) {
+ var converted = toMd(cn[i], depth + 1);
+ children += converted;
+ if (cells && cn[i].nodeType === 1) cells.push(converted);
+ }
+ }
children = children.replace(/\n{3,}/g, '\n\n');
switch(tag) {
case 'h1': return '\n# ' + children.trim() + '\n\n';
@@ -42,18 +67,14 @@ pub const HTML_TO_MARKDOWN_JS: &str = r#"
case 'ul': case 'ol':
return '\n' + children + '\n';
case 'li':
- var parent = el.parentNode;
- var isOrdered = parent && parent.tagName && parent.tagName.toLowerCase() === 'ol';
+ var listParent = el.parentNode;
+ var isOrdered = listParent && listParent.tagName && listParent.tagName.toLowerCase() === 'ol';
var bullet = isOrdered ? '1. ' : '- ';
return bullet + children.trim() + '\n';
case 'table': return '\n' + children + '\n';
case 'thead': case 'tbody': case 'tfoot': return children;
case 'tr':
- var cells = [];
- var tds = el.childNodes || [];
- for (var j = 0; j < tds.length; j++) {
- if (tds[j].nodeType === 1) cells.push(toMd(tds[j], depth).trim());
- }
+ for (var j = 0; j < cells.length; j++) cells[j] = cells[j].trim();
return '| ' + cells.join(' | ') + ' |\n';
case 'th': case 'td': return children;
case 'script': case 'style': case 'noscript': case 'link': case 'meta': return '';
diff --git a/crates/obscura-js/src/runtime.rs b/crates/obscura-js/src/runtime.rs
index f8ac218d..09daa053 100644
--- a/crates/obscura-js/src/runtime.rs
+++ b/crates/obscura-js/src/runtime.rs
@@ -25414,6 +25414,122 @@ mod tests {
);
}
+ #[test]
+ fn test_html_to_markdown_deep_dom() {
+ let mut rt = setup_runtime("<html><body></body></html>");
+ rt.evaluate(r#"(() => {
+ let child = document.createTextNode('deep leaf');
+ for (let i = 0; i < 12000; i++) {
+ const parent = document.createElement('span');
+ parent.appendChild(child);
+ child = parent;
+ }
+ document.body.appendChild(child);
+ })()"#).unwrap();
+ assert_eq!(rt.evaluate(crate::HTML_TO_MARKDOWN_JS).unwrap(), serde_json::json!("deep leaf"));
+ }
+
+ #[test]
+ fn test_html_to_markdown_deep_tables() {
+ let mut rt = setup_runtime("<html><body></body></html>");
+ rt.evaluate(r#"(() => {
+ let child = document.createTextNode('leaf');
+ for (let i = 0; i < 180; i++) {
+ const table = document.createElement('table');
+ const row = document.createElement('tr');
+ const cell = document.createElement('td');
+ cell.appendChild(child);
+ row.appendChild(cell);
+ table.appendChild(row);
+ child = table;
+ }
+ document.body.appendChild(child);
+ })()"#).unwrap();
+ let expected = format!("{}leaf{}", "| ".repeat(180), " |".repeat(180));
+ assert_eq!(rt.evaluate(crate::HTML_TO_MARKDOWN_JS).unwrap(), serde_json::json!(expected));
+ }
+
+ #[test]
+ fn test_html_to_markdown_deep_subtree_formatting() {
+ let mut rt = setup_runtime("<html><body></body></html>");
+ for depth in [127, 128, 129, 130] {
+ rt.evaluate(&format!(r#"(() => {{
+ document.body.innerHTML = '';
+ let child = document.createElement('span');
+ child.innerHTML = '<h1>Title</h1><p>Hello <strong>world</strong></p><table><tr><td>A</td><td>B</td></tr></table>';
+ for (let i = 0; i < {depth}; i++) {{
+ const parent = document.createElement('span');
+ parent.appendChild(child);
+ child = parent;
+ }}
+ document.body.appendChild(child);
+ }})()"#)).unwrap();
+ assert_eq!(rt.evaluate(crate::HTML_TO_MARKDOWN_JS).unwrap(),
+ serde_json::json!("# Title\n\nHello **world**\n\n| A | B |"), "depth {depth}");
+ }
+ }
+
+ #[test]
+ fn test_html_to_markdown_row_ignores_non_element_children() {
+ let mut rt = setup_runtime("<html><body></body></html>");
+ rt.evaluate(r#"(() => {
+ const table = document.createElement('table');
+ const row = document.createElement('tr');
+ row.appendChild(document.createTextNode('ignored'));
+ row.appendChild(document.createComment('ignored'));
+ const cell = document.createElement('td');
+ cell.textContent = 'A';
+ row.appendChild(cell);
+ const span = document.createElement('span');
+ span.textContent = 'B';
+ row.appendChild(span);
+ table.appendChild(row);
+ document.body.appendChild(table);
+ })()"#).unwrap();
+ assert_eq!(rt.evaluate(crate::HTML_TO_MARKDOWN_JS).unwrap(), serde_json::json!("| A | B |"));
+ }
+
+ #[test]
+ fn test_html_to_markdown_visits_nested_table_elements_once() {
+ let mut rt = setup_runtime("<html><body></body></html>");
+ let expected_reads = rt.evaluate(r#"(() => {
+ let child = document.createTextNode('leaf');
+ for (let i = 0; i < 12; i++) {
+ const table = document.createElement('table');
+ const row = document.createElement('tr');
+ const cell = document.createElement('td');
+ cell.appendChild(child);
+ row.appendChild(cell);
+ table.appendChild(row);
+ child = table;
+ }
+ document.body.appendChild(child);
+ const expected = document.body.querySelectorAll('*').length + 1;
+ const descriptor = Object.getOwnPropertyDescriptor(Node.prototype, 'childNodes');
+ globalThis.markdownChildReads = 0;
+ Object.defineProperty(Node.prototype, 'childNodes', {
+ configurable: true,
+ get() {
+ markdownChildReads++;
+ return descriptor.get.call(this);
+ }
+ });
+ return expected;
+ })()"#).unwrap();
+ let md = rt.evaluate(crate::HTML_TO_MARKDOWN_JS).unwrap();
+ assert!(md.as_str().unwrap().contains("leaf"));
+ assert_eq!(rt.evaluate("markdownChildReads").unwrap(), expected_reads);
+ }
+
+ #[test]
+ fn test_html_to_markdown_table_output() {
+ let mut rt = setup_runtime(
+ "<html><body><table><tr><th>A</th><th>B</th></tr><tr><td>one <strong>bold</strong></td><td><a href='/two'>two</a></td></tr></table><p>tail</p></body></html>",
+ );
+ assert_eq!(rt.evaluate(crate::HTML_TO_MARKDOWN_JS).unwrap(),
+ serde_json::json!("| A | B |\n| one **bold** | [two](/two) |\n\ntail"));
+ }
+
#[test]
fn test_html_to_markdown_headings() {
let mut rt =
diff --git a/docs/Markdown-extraction.md b/docs/Markdown-extraction.md
index b3fb188f..040bf3ad 100644
--- a/docs/Markdown-extraction.md
+++ b/docs/Markdown-extraction.md
@@ -1,5 +1,9 @@
`--dump markdown` converts the rendered page to markdown.
+Extraction switches to an iterative tree walk for deep subtrees, so deeply
+nested DOMs do not exhaust the JavaScript call stack. Nested table cells are
+converted once and reused when assembling their rows.
+
```bash
obscura fetch https://example.com --dump markdown
```