Act

apify/example-selenium

  • Builds
  • latest 0.0.1 / 2017-11-02
  • Created 2017-11-02
  • Last modified 2017-11-02
  • grade 2

Description

Example of loading a web page in headless Chrome using Selenium Webdriver.


API

To run the act, send a HTTP POST request to:

https://api.apify.com/v2/acts/apify~example-selenium/runs?token=<YOUR_API_TOKEN>

The POST payload will be passed as input for the act. For more information, read the docs.


Source code

Based on the apify/actor-node-chrome Docker image (see docs).

const Apify = require('apify');
const { Capabilities, Builder, By, until, logging } = require('selenium-webdriver');
const chrome = require('selenium-webdriver/chrome');

// Enable logging if needed
// logging.installConsoleHandler();
// logging.getLogger('webdriver.http').setLevel(logging.Level.ALL);

Apify.main(async () => {
    // See https://github.com/SeleniumHQ/selenium/wiki/DesiredCapabilities for reference.
    const capabilities = new Capabilities();
    capabilities.set('browserName', 'chrome');

    // Chrome-specific options
    // By default, Selenium already defines a long list of command-line options
    // to enable browser automation, here we add a few other ones
    // (inspired by Lighthouse, see lighthouse/lighthouse-cli/chrome-launcher)
    const chromeOptions = new chrome.Options();
    chromeOptions.addArguments('--disable-translate');
    chromeOptions.addArguments('--safebrowsing-disable-auto-update');
    if (process.env.APIFY_HEADLESS) {
        chromeOptions.addArguments('--headless', '--disable-gpu', '--no-sandbox');
    }

    const builder = new Builder();
    const webDriver = builder
                    .setChromeOptions(chromeOptions)
                    .withCapabilities(capabilities)
                    .build();

    await webDriver.get('http://www.example.com');
                   
    const html = await webDriver.executeScript(() => {
        return document.documentElement.innerHTML;
    });
    
    console.log(html);
});