跳到主要内容
版本: 23.11.1

开始使用

使用其他浏览器测试框架的人会对 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();
})();

有关更深入的用法,请查看我们的文档示例