Crawlee—A web scraping and browser automation library for Node.js to build reliable crawlers. In JavaScript and TypeScript. Extract data for AI, LLMs, RAG, or GPTs. Download HTML, PDF, JPG, PNG, and other files from websites. Works with Puppeteer, Playwright, Cheerio, JSDOM, and raw HTTP. Both headful and headless mode. With proxy rotation.
TypeScript apifyautomationcrawlercrawlingheadlessheadless-chromejavascriptnodejsnpmplaywrightpuppeteerscraperscrapingtypescriptweb-crawlerweb-crawlingweb-scraping
Development of Chrome/Selenium integration
Jan Curn91131e1b6cfe
diff --git a/.travis.yml b/.travis.ymlindex f4ef1e036..5b830ff72 100644--- a/.travis.yml+++ b/.travis.yml@@ -1,3 +1,11 @@+before_install:+ - curl -sS https://dl-ssl.google.com/linux/linux_signing_key.pub | sudo apt-key add -+ - sudo apt-get -qq update+ - sudo apt-get install -y google-chrome-beta+ - curl -sS http://chromedriver.storage.googleapis.com/2.29/chromedriver_linux64.zip > /tmp.zip+ - unzip /tmp.zip+ - rm /tmp.zip+ - mv /chromedriver /binlanguage: node_jsnode_js:- "7"diff --git a/package.json b/package.jsonindex defcf3107..c461fa258 100644--- a/package.json+++ b/package.json@@ -64,5 +64,10 @@"sinon-stub-promise": "^4.0.0","tmp": "^0.0.31","underscore": "^1.8.3"+ },+ "optionalDependencies": {+ "chrome-remote-interface": "^0.23.0",+ "lighthouse": "^2.0.0",+ "selenium-webdriver": "^3.4.0"}}diff --git a/src/browser.js b/src/browser.jsnew file mode 100644index 000000000..6e07838f0--- /dev/null+++ b/src/browser.js@@ -0,0 +1,128 @@+import { ChromeLauncher } from 'lighthouse/lighthouse-cli/chrome-launcher';+import { APIFY_ENV_VARS } from './constants';+import { newPromise, nodeifyPromise } from './utils';++/* global process, require */++// interesting resources:+// https://chromium.googlesource.com/chromium/src/+/master/docs/linux_debugging.md+// http://peter.sh/experiments/chromium-command-line-switches/#user-agent+// https://github.com/SeleniumHQ/selenium/tree/master/javascript/node/selenium-webdriver/example++// logging.installConsoleHandler();+// logging.getLogger('webdriver.http').setLevel(logging.Level.ALL);++/**+ * Gets the default options for the browse() function, generated from current process environment+ * variables. This is function to enable unit testing.+ */+export const getDefaultBrowseOptions = () => {+ return {+ headless: !!process.env[APIFY_ENV_VARS.HEADLESS],+ browser: 'chrome', // Current default+ };+};+++/**+ * Represents a single web browser proces.+ * Currently it is just a thin wrapper of Selenium's WebDriver instance.+ */+export class Browser {+ constructor(webDriver) {+ this.webDriver = webDriver;+ }++ close() {+ return newPromise()+ .then(() => {+ if (this.webDriver) {+ this.webDriver.quit();+ this.webDriver = null;+ }+ });+ }+}+++/**+ * Opens a new web browser, which is attached to Apifier debugger so that snapshots are sent to Run console (TODO).+ * Internally, this function calls Selenium WebDrivers's Builder command to create a new WebDriver instance.+ * (see http://seleniumhq.github.io/selenium/docs/api/javascript/module/selenium-webdriver/index_exports_Builder.html)+ * The result of the function is a new instance of the Browser class.+ * @param url The start URL to open. Defaults to about:blank+ * @param options Configuration options, their defaults are provided by the getDefaultBrowseOptions() function.+ * @param callback Optional callback.+ * @return Returns a promise if no callback was provided, otherwise the return value is not defined.+ */+export const browse = (url, options = null, callback = null) => {+ url = url || 'about:blank';+ options = Object.assign(getDefaultBrowseOptions(), options);++ // This is an optional dependency because it is quite large, only require it when used!+ const { Builder } = require('selenium-webdriver'); // eslint-disable-line global-require+ const chrome = require('selenium-webdriver/chrome'); // eslint-disable-line global-require++ // 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 chromeOpts = new chrome.Options();+ // Disable built-in Google Translate service+ chromeOpts.addArguments('--disable-translate');+ // Disable fetching safebrowsing lists, likely redundant due to disable-background-networking+ chromeOpts.addArguments('--safebrowsing-disable-auto-update');+ // Run in headless mode if requested+ if (options.headless) chromeOpts.addArguments('--headless', '--disable-gpu', '--no-sandbox');++ const webDriver = new Builder()+ .forBrowser(options.browser)+ .setChromeOptions(chromeOpts)+ .build();++ const browser = new Browser(webDriver);++ const promise = newPromise()+ .then(() => webDriver.get(url))+ .then(() => {+ return browser;+ });++ return nodeifyPromise(promise, callback);+};+++/**+ * Launches a debugging instance of Chrome on port 9222, without Selenium.+ * This code is kept here for legacy reasons, it's not used.+ * @param {boolean=} headless True (default) to launch Chrome in headless mode.+ * Set to false to launch Chrome normally.+ * @return {Promise<ChromeLauncher>}+ */+export const launchChrome = (headless = !!process.env.APIFY_HEADLESS) => {+ // code inspired by https://developers.google.com/web/updates/2017/04/headless-chrome+ // TODO: enable other options e.g. userAgent, windowHeight, windowWidth, proxy++ const launcher = new ChromeLauncher({+ port: 9222,+ autoSelectChrome: true, // False to manually select which Chrome install.+ additionalFlags: [+ '--window-size=412,732',+ '--disable-gpu',+ headless ? '--headless' : '',+ ],+ });++ return newPromise()+ .then(() => {+ return launcher.run();+ })+ .then(() => {+ return launcher;+ })+ .catch((err) => {+ // Kill Chrome if there's an error.+ return launcher.kill().then(() => {+ throw err;+ }, console.error);+ });+};diff --git a/src/constants.js b/src/constants.jsindex a838447be..00620c79c 100644--- a/src/constants.js+++ b/src/constants.js@@ -26,6 +26,7 @@ export const APIFY_ENV_VARS = {DEFAULT_KEY_VALUE_STORE_ID: 'APIFY_DEFAULT_KEY_VALUE_STORE_ID',WATCH_FILE: 'APIFY_WATCH_FILE',API_BASE_URL: 'APIFY_API_BASE_URL',+ HEADLESS: 'APIFY_HEADLESS',};diff --git a/src/index.js b/src/index.jsindex 79b2168d1..dbcbb50bb 100644--- a/src/index.js+++ b/src/index.js@@ -2,6 +2,9 @@ import EventEmitter from 'events';import { setPromisesDependency, getPromisesDependency } from './utils';import { main, readyFreddy, getContext, getInput, setOutput, apifyClient } from './actor';+import { browse } from './browser';++/* globals module */// Publicly available functionsconst Apifier = {@@ -12,6 +15,7 @@ const Apifier = {readyFreddy,setPromisesDependency,getPromisesDependency,+ browse,client: apifyClient,events: new EventEmitter(),};diff --git a/src/utils.js b/src/utils.jsindex 1874eb572..91e98e8a5 100644--- a/src/utils.js+++ b/src/utils.js@@ -53,9 +53,7 @@ export const nodeifyPromise = (promise, callback) => {if (!promise) throw new Error('The "promise" parameter must be provided.');if (callback) {- promise- .then(result => callback(null, result))- .catch(err => callback(err));+ promise.then(result => callback(null, result), err => callback(err));} else {return promise;}diff --git a/test/actor.js b/test/actor.jsindex d695608f3..19245785c 100644--- a/test/actor.js+++ b/test/actor.js@@ -5,10 +5,10 @@ import sinon from 'sinon';import tmp from 'tmp';import Promise from 'bluebird';-// NOTE: use require() here because this is how its done in acts+// NOTE: test use of require() here because this is how its done in actsconst Apifier = require('../build/index');-/* global process */+/* global process, describe, it */// TODO: override console.log() to test the error messages (now they are printed to console)// TODO: test callback version of functions!!!diff --git a/test/browser.js b/test/browser.jsnew file mode 100644index 000000000..bf3700a24--- /dev/null+++ b/test/browser.js@@ -0,0 +1,152 @@+import { expect } from 'chai';+import CDP from 'chrome-remote-interface';+import { getDefaultBrowseOptions, launchChrome } from '../build/browser';+import Apifier from '../build/index';+++describe('getDefaultBrowseOptions()', () => {+ it('it works', () => {+ process.env.APIFY_HEADLESS = '1';+ const opts1 = getDefaultBrowseOptions();+ expect(opts1).to.eql({+ browser: 'chrome',+ headless: true,+ });++ delete process.env.APIFY_HEADLESS;+ const opts2 = getDefaultBrowseOptions();+ expect(opts2).to.eql({+ browser: 'chrome',+ headless: false,+ });+ });+});+++describe('Apifier.browse()', () => {+ it('opens about:blank with no args', () => {+ process.env.APIFY_HEADLESS = '1';+ let browser;+ return Apifier.browse()+ .then((res) => {+ browser = res;+ expect(browser.constructor.name).to.eql('Browser');+ return browser.webDriver.getCurrentUrl();+ })+ .then((url) => {+ expect(url).to.eql('about:blank');+ return browser.close();+ });+ }).timeout(10000);++ it('opens https://www.example.com in headless mode', () => {+ delete process.env.APIFY_HEADLESS;+ let browser;+ return Apifier.browse('https://www.example.com', { headless: true })+ .then((res) => {+ browser = res;+ expect(browser.constructor.name).to.eql('Browser');+ return browser.webDriver.getCurrentUrl();+ })+ .then((url) => {+ expect(url).to.eql('https://www.example.com/');+ return browser.close();+ });+ }).timeout(10000);+});+++describe('launchChrome()', () => {+ let launcher;++ before(() => {+ process.env.APIFY_HEADLESS = '1';+ return launchChrome().then((l) => {+ launcher = l;+ });+ });++ it('reports head-less version', () => {+ return Promise.resolve().then(() => {+ return CDP.Version();+ })+ .then((version) => {+ expect(version.Browser).to.contain('HeadlessChrome');+ // console.dir(version);+ });+ });++ it('opens http://www.example.com', () => {+ function onPageLoad(Runtime) {+ const js = 'document.querySelector("title").textContent';++ // Evaluate the JS expression in the page.+ return Runtime.evaluate({ expression: js })+ .then((result) => {+ console.log(`Title of page: ${result.result.value}`);+ });+ }++ return new Promise((resolve, reject) => {+ CDP((protocol) => {+ // Extract the parts of the DevTools protocol we need for the task.+ // See API docs: https://chromedevtools.github.io/devtools-protocol/+ const { Page, Runtime } = protocol;++ // First, need to enable the domains we're going to use.+ Promise.all([+ Page.enable(),+ Runtime.enable(),+ ])+ .then(() => {+ Page.navigate({ url: 'https://www.example.com/' });++ // Wait for window.onload before doing stuff.+ Page.loadEventFired(() => {+ onPageLoad(Runtime)+ .then(() => {+ protocol.close();+ resolve();+ });+ });+ });+ })+ .on('error', reject);+ });+ }).timeout(10000);++ // it('test github requests', () => {+ // return new Promise((resolve, reject) => {+ // CDP((client) => {+ // // extract domains+ // const { Network, Page } = client;+ // // setup handlers+ // Network.requestWillBeSent((params) => {+ // console.log(params.request.url);+ // });+ // Page.loadEventFired(() => {+ // client.close();+ // });+ // // enable events then start!+ // Promise.all([+ // Network.enable(),+ // Page.enable(),+ // ]).then(() => {+ // return Page.navigate({ url: 'https://github.com' });+ // }).catch((err) => {+ // console.error(err);+ // client.close();+ // resolve();+ // });+ // }).on('error', (err) => {+ // // cannot connect to the remote endpoint+ // console.error(err);+ // reject(err);+ // });+ // });+ // });++ after(() => {+ return launcher.kill();+ });+});diff --git a/test/utils.js b/test/utils.jsindex 7203b34a7..31a705a7a 100644--- a/test/utils.js+++ b/test/utils.js@@ -3,7 +3,7 @@ import { expect } from 'chai';import * as utils from '../build/utils';import Apifier from '../build/index';-/* global process */+/* global process, describe, it */// TODO: run tests against build scripts too!