開始使用
使用過其他瀏覽器測試框架的人會對 Puppeteer 感到熟悉。您會啟動/連線一個瀏覽器,建立一些頁面,然後使用 Puppeteer 的 API 來操作它們。
以下範例會在 developer.chrome.com 上搜尋包含文字 "automate beyond recorder" 的部落格文章,點擊第一個結果並印出部落格文章的完整標題。
import puppeteer from 'puppeteer';
(async () => {
// Launch the browser and open a new blank page
const browser = await puppeteer.launch();
const page = await browser.newPage();
// Navigate the page to a URL
await page.goto('https://developer.chrome.com/');
// Set screen size
await page.setViewport({width: 1080, height: 1024});
// Type into search box
await page.type('.devsite-search-field', 'automate beyond recorder');
// Wait and click on first result
const searchResultSelector = '.devsite-result-item-link';
await page.waitForSelector(searchResultSelector);
await page.click(searchResultSelector);
// Locate the full title with a unique string
const textSelector = await page.waitForSelector(
'text/Customize and automate',
);
const fullTitle = await textSelector?.evaluate(el => el.textContent);
// Print the full title
console.log('The title of this blog post is "%s".', fullTitle);
await browser.close();
})();