Puppeteer 简明教程
Puppeteer - Basic Commands
下面列出了一些 Puppeteer 的基本命令 −
Some of the basic commands of Puppeteer are listed below −
url()
此命令用于获取浏览器中当前启动的应用程序的 URL。
This command is used to obtain the URL of the application currently launched in the browser.
content()
此命令用于获取页面源代码。
This command is used to obtain the page source code.
Syntax
其语法如下:
The syntax is as follows −
await page.content()
首先,按照人偶基本测试章节执行步骤 1 至 2,如下所示 -
To begin, follow Steps 1 to 2 from the Chapter of Basic Test on Puppeteer which are as follows −
Step 1 - 在创建 node_modules 文件夹的目录中创建一个新文件(人偶和人偶核已安装的位置)。
Step 1 − Create a new file within the directory where the node_modules folder is created (location where the Puppeteer and Puppeteer core have been installed).
人偶安装的详情在人偶安装篇章中进行了讨论。
The details on Puppeteer installation is discussed in the Chapter of Puppeteer Installation.
右击创建 node_modules 文件夹的文件夹,然后点击新建文件按钮。
Right-click on the folder where the node_modules folder is created, then click on the New file button.

Step 2 - 输入文件名,如 testcase1.js。
Step 2 − Enter a filename, say testcase1.js.

Step 3 - 将以下代码添加到新创建的 testcase1.js 文件中。
Step 3 − Add the below code within the testcase1.js file created.
//adding Puppeteer library
const pt = require('puppeteer');
pt.launch().then(async browser => {
//browser new page
const p = await browser.newPage();
//set viewpoint of browser page
await p.setViewport({ width: 1000, height: 500 })
//launch URL
await p.goto('https://www.tutorialspoint.com/questions/index.php')
//obtain page title
console.log("Page title: " + await p.title())
//obtain URL
console.log("Url: " + await p.url())
//browser close
await browser.close()
})
Step 4 - 使用以下命令执行代码 -
Step 4 − Execute the code with the command given below −
node <filename>
因此,在我们的示例中,我们将运行以下命令 -
So in our example, we shall run the following command −
node testcase1.js

成功执行命令后,页面标题——最佳技术问题和答案被打印在控制台中。此外,URL—— www.tutorialspoint.com/questions/index.php 被打印在控制台中。执行已在无头模式下进行。
After the command has been successfully executed, the page title - The Best Technical Questions and Answers gets printed in the console. Also, the URL - www.tutorialspoint.com/questions/index.php gets printed in the console. The execution has happened in the headless mode.