Playwrightでローカルファイルを読み込む
typescript 5.0.4
playwright 1.32.2
まとめ
page.goto(htmlPath)
でHTMLファイルのパスを渡す。
そもそも
利用しているライブラリがplaywright
ではなく、@playwright/test
なのであれば設定のbaseUrl
を利用すれば実現できる。
playwright
はブラウザ操作APIで、
@playwright/test
はそのplaywright
を用いたテストランナー
サンプル
<html>
<head>
<meta charset="utf-8" />
<title>Playwrightでローカルファイルを読み込む</title>
</head>
<body>
<div>
<p id="p1">hoge</p>
<p>fuga</p>
<p>hoge</p>
</div>
</body>
</html>
import path from "path";
import { chromium } from "playwright";
void (async () => {
const browser = await chromium.launch();
const context = await browser.newContext();
const page = await context.newPage();
const htmlPath = `file://${path.join(__dirname, `../resources/index.html`)}`;
await page.goto(htmlPath);
const title = await page.title();
console.log(title);
const p1 = await page.locator('p#p1').innerText();
console.log(p1);
const countOfHoge = await page.locator('p:has-text("hoge")').count();
console.log(countOfHoge)
await browser.close();
})();
↓実行結果↓
Playwrightでローカルファイルを読み込む
hoge
2