There are several tables on a page. I'm. trying to get City/Town.
<table class="table" style="margin-top: 35px;">
<thead>
<!--<tr>
<th scope="col"></th>
<th scope="col"></th>
</tr>-->
</thead>
<tbody>
<tr>
<td>Street</td>
<td>61 Essex St</td>
</tr>
<tr>
<td>City/Town</td>
<td>Lynn</td>
</tr>
<tr>
<td>State/Province/Region</td>
<td>Maine</td>
</tr>
<tr>
<td>Zip/Postal Code</td>
<td>01902</td>
</tr>
</tbody>
</table>
I know I can get the element for the cell item above what I need.
let foo = page.locator(`test=City/Town`)
but I'm not sure how to get the next data cell. I googled and tried:
let foo = page.locator(`td:below(:text("street"))`).innerText()
but that didn't work. I also tried:
let foo = page.locator(`td:near(:text'("Street"))+td`).first().textContent()
this didn't work for me either. I tried some other variations.
Can you help a clueless man out?
You can use the adjacent sibling combinator: page.locator('td:text("City/Town") + td')
.
Example:
const playwright = require("playwright"); // 1.23.3
const html = `<!DOCTYPE html><html><body>
<table class="table" style="margin-top: 35px;">
<thead>
<!--<tr>
<th scope="col"></th>
<th scope="col"></th>
</tr>-->
</thead>
<tbody>
<tr>
<td>Street</td>
<td>61 Essex St</td>
</tr>
<tr>
<td>City/Town</td>
<td>Lynn</td>
</tr>
<tr>
<td>State/Province/Region</td>
<td>Maine</td>
</tr>
<tr>
<td>Zip/Postal Code</td>
<td>01902</td>
</tr>
</tbody>
</table>
</body></html>`;
let browser;
(async () => {
browser = await playwright.chromium.launch();
const page = await browser.newPage();
await page.setContent(html);
const result = await page.locator('td:text("City/Town") + td')
.textContent();
console.log(result); // => Lynn
})()
.catch(err => console.error(err))
.finally(() => browser?.close());