Sample-Code

Every virtual machine comes with some basic sample code. With this samples you can learn the most common browser operations. Puppeteer can run two browsers: Chromium and Chrome.

The below sample code is for Ubuntu server without a graphical user interface. Sample code for other OS and browsers can be found within the virtual machines.



Init Puppeteer:

First the pre-installed Puppeteer nodejs module needs to be included. Afterwards, the browser and a new page will be opened with the defined screen size. The last line closes the browser instance again.



const puppeteer = require('puppeteer');
 
(async () => {
  const browser = await puppeteer.launch();
  const page = await browser.newPage();

  // set browser size
  await page.setViewport({
    width: 1500,
    height: 700,
  });
  
  // following actions
  
  await browser.close();
}
const puppeteer = require('puppeteer');
 
(async () => {
  const browser = await puppeteer.launch({executablePath: '/usr/bin/google-chrome'});
  const page = await browser.newPage();

  // set browser size
  await page.setViewport({
    width: 1500,
    height: 700,
  });
  
  // following actions
  
  await browser.close();
}

Navigate to URL:

We now navigate to this web page.

await page.goto('https://selenium.cloud/doc/puppeteer-samples.html');

Take a screenshot:

Let us take a screenshot to prove we are on the correct page. This also works in headless browser!

await page.screenshot({path: 'screenshot1.png'});

Click on element via XPath:

Before we can click an element on the page, we need to locate it. There are different methods to achieve this, the most common way is via XPath.
There are dozens of good tools to get the XPath of elements, Chrome has also one built-in.

Below you find a screenshot of the popular ChroPath plugin:

<


Learn more about XPath here.

// clicking on element by relative xpath
var [button] = await page.$x('//a[@id="chrome-tab"]');
if (button) {
  await button.click();
}

// clicking on element by absolute xpath
[button] = await page.$x('//main/section/div/ul/li[1]/a');
if (button) {
  await button.click();
}

Send string to input field and open popup:

Now we type in some text into a text field. Afterwards we click on the button which opens a small popup.

await page.$eval("input[id=text-field]", el => el.value = 'Sent from Puppeteer');
[button] = await page.$x("//button[contains(text(),'Click me!')]");
if (button) {
  await button.click();
}


Get text of element:

The last code block shows you, how you can pull out the visible text of an element.

const text = await page.$eval('div[id=modalbody-text]', el => el.innerText)
console.log("Text of popup: "+text);