Newsletter
TechAnV Blog
Get updates on security engineering, Rust, eBPF, and DevSecOps. No spam, unsubscribe anytime.
Check your inbox and click the confirmation link to complete your subscription.
Testing HTML tables with Playwright Python#
I figured out this pattern today for testing an HTML table dynamically added to a page by JavaScript, using Playwright Python:
1table_js = """2function tableToJson() {3 return Array.from(document.querySelectorAll("table")).map((table) => {4 return {5 headers: Array.from(table.querySelectorAll("th")).map((th) =>6 th.textContent.trim(),7 ),8 rows: Array.from(table.querySelectorAll("tr"))9 .slice(1)10 .map((tr) => {11 return Array.from(tr.querySelectorAll("td")).map((cell) =>12 cell.textContent.trim(),13 );14 }),15 };16 });17}18"""19
20
21def test_search(ds_server, page):22 page.goto(ds_server + "/-/search?q=cleo")23 # Should show search results, after fetching them24 page.wait_for_selector("table")25 tables = page.evaluate(table_js)26 assert tables == [27 {28 "headers": ["rowid", "name", "description"],29 "rows": [["1", "Cleo", "A medium sized dog"]],30 },31 ]ds_server there is a fixture that starts Datasette running on a local port and returns the base URL for the instance.
The pattern I’m interested in is table_js - where you define a block of JavaScript to run on the page that returns a JSON-style dictionary, then use page.evaluate(table_js) to get the result back as a Python data structure which you can use in assertions.
The full test can be found here.
Newsletter
TechAnV Blog
Get updates on security engineering, Rust, eBPF, and DevSecOps. No spam, unsubscribe anytime.
Check your inbox and click the confirmation link to complete your subscription.