Skip to content

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.

Refactor useChrome test, remove Selenium support

Ondra Urban3724e179d382
diff --git a/src/index.js b/src/index.js
index cf4727dac..78fb59353 100644
--- a/src/index.js
+++ b/src/index.js
@@ -16,7 +16,6 @@ import { RequestList, openRequestList } from './request_list';
import { openRequestQueue } from './request_queue';
import SettingsRotator from './settings_rotator';
import { apifyClient, getMemoryInfo, isAtHome, publicUtils, logSystemInfo } from './utils';
-import { browse, launchWebDriver } from './webdriver';
import { puppeteerUtils } from './puppeteer_utils';
import { socialUtils } from './utils_social';
import { enqueueLinks } from './enqueue_links';
@@ -93,9 +92,6 @@ module.exports = {
LiveViewServer,
- browse,
- launchWebDriver,
-
utils: Object.assign(publicUtils, {
puppeteer: puppeteerUtils,
social: socialUtils,
diff --git a/src/webdriver.js b/src/webdriver.js
deleted file mode 100644
index ab53cdeaf..000000000
--- a/src/webdriver.js
+++ /dev/null
@@ -1,366 +0,0 @@
-// import { ChromeLauncher } from 'lighthouse/lighthouse-cli/chrome-launcher';
-import { anonymizeProxy, closeAnonymizedProxy } from 'proxy-chain';
-import { ENV_VARS } from 'apify-shared/consts';
-import { DEFAULT_USER_AGENT } from './constants';
-import { newPromise } 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);
-
-// TODO: on first use of Apify.browse(), print out the version of Chrome and ChromeDriver
-
-/**
- * Gets the default options for the browse() function, generated from current process environment
- * variables. This is function to enable unit testing.
- *
- * @ignore
- */
-export const getDefaultBrowseOptions = () => {
- return {
- headless: process.env[ENV_VARS.HEADLESS] === '1' && process.env[ENV_VARS.XVFB] !== '1',
- browserName: 'chrome',
- proxyUrl: null,
- userAgent: null,
- };
-};
-
-const isWin = process.platform === 'win32';
-
-/**
- * Represents a single web browser process.
- * Currently it is just a thin wrapper of Selenium's WebDriver instance.
- *
- * @ignore
- */
-export class Browser {
- constructor(options) {
- this.options = Object.assign(getDefaultBrowseOptions(), options);
-
- // This is an optional dependency because it is quite large, only require it when used
- const { Capabilities, Builder } = require('selenium-webdriver'); // eslint-disable-line global-require
- const chrome = require('selenium-webdriver/chrome'); // eslint-disable-line global-require
-
- this.anonymizedProxyUrl = null;
-
- // logging.installConsoleHandler();
- // logging.getLogger('webdriver.http').setLevel(logging.Level.ALL);
-
- // See https://github.com/SeleniumHQ/selenium/wiki/DesiredCapabilities for reference.
- this.capabilities = new Capabilities();
- this.capabilities.set('browserName', this.options.browserName);
-
- // 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)
- this.chromeOptions = new chrome.Options();
- this.chromeOptions.addArguments('--disable-translate');
- this.chromeOptions.addArguments('--safebrowsing-disable-auto-update');
- if (this.options.headless) {
- this.chromeOptions.addArguments('--headless', '--no-sandbox');
- if (isWin) {
- // Temporarily needed on Windows
- this.chromeOptions.addArguments('--disable-gpu');
- }
- }
- this.chromeOptions.addArguments(`--user-agent=${this.options.userAgent || DEFAULT_USER_AGENT}`);
-
- if (this.options.extraChromeArguments) {
- this.chromeOptions.addArguments(this.options.extraChromeArguments);
- }
-
- this.builder = new Builder();
-
- // Instance of Selenium's WebDriver
- this.webDriver = null;
- }
-
- _initialize() {
- let promise = null;
-
- // Applies options.proxyUrl setting to the WebDriver's Capabilities and Chrome Options.
- // For proxy servers with authentication, this class starts a local proxy server
- // NOTE: to view effective proxy settings in Chrome, open chrome://net-internals/#proxy
- if (this.options.proxyUrl) {
- // NOTE: call anonymizeProxy() outside of promise, so that errors in proxyUrl are thrown!
- promise = anonymizeProxy(this.options.proxyUrl)
- .then((result) => {
- this.anonymizedProxyUrl = result;
-
- if (/^chrome$/i.test(this.options.browserName)) {
- // In Chrome, Capabilities.setProxy() has no effect,
- // so we setup the proxy manually
- this.chromeOptions.addArguments(`--proxy-server=${this.anonymizedProxyUrl}`);
- } else {
- const proxyConfig = {
- proxyType: 'MANUAL',
- httpProxy: this.anonymizedProxyUrl,
- sslProxy: this.anonymizedProxyUrl,
- ftpProxy: this.anonymizedProxyUrl,
- };
- this.capabilities.setProxy(proxyConfig);
- }
- });
- }
-
- // Ensure that the returned promise is of type set in setPromiseDependency()
- return newPromise()
- .then(() => {
- return promise;
- })
- .then(() => {
- this.webDriver = this.builder
- .setChromeOptions(this.chromeOptions)
- .withCapabilities(this.capabilities)
- .build();
- })
- .then(() => {
- return this;
- });
- }
-
- close() {
- return newPromise()
- .then(() => {
- if (this.webDriver) {
- return this.webDriver.quit();
- }
- })
- .then(() => {
- if (this.anonymizedProxyUrl) {
- return closeAnonymizedProxy(this.anonymizedProxyUrl, true);
- }
- })
- .then(() => {
- this.webDriver = null;
- });
- }
-}
-
-/**
- * Normalizes arguments for Apify.browse(), fills correctly default values.
- * The function is exported to allow unit testing.
- *
- * @param {String} [url]
- * @param {Object} [options]
- *
- * @ignore
- */
-export const processBrowseArgs = (url, options) => {
- if (typeof (url) === 'object') {
- options = url;
- url = null;
- }
- options = Object.assign({}, options);
- options.url = url || options.url || 'about:blank';
-
- if (typeof (options.url) !== 'string') throw new Error('Invalid "url" provided.');
-
- return { options };
-};
-
-/*
-OLD INFO FROM README:
-### Browser
-
-Apify runtime optionally depends on
-the [selenium-webdriver](https://www.npmjs.com/package/selenium-webdriver) package that enables
-automation of a web browser.
-The simplest way to launch a new web browser is using the `Apify.browse([url,] [options)`
-function. For example:
-
-```javascript
-const browser = await Apify.browse('https://www.example.com/');
-```
-
-or
-
-```javascript
-const browser = await Apify.browse({
- url: 'https://www.example.com/',
- userAgent: 'MyCrawlingBot/1.23',
-});
-```
-
-The `options` parameter controls settings of the web browser and it has the following properties:
-
-```javascript
-{
- // Initial URL to open. Note that the url argument in Apify.browse() overrides this value.
- // The default value is 'about:blank'
- url: String,
-
- // The type of the web browser to use.
- // See https://github.com/SeleniumHQ/selenium/wiki/DesiredCapabilities for possible options.
- // The default value is 'chrome', which is currently the only fully-supported browser.
- browserName: String,
-
- // Indicates whether the browser should be opened in headless mode (i.e. without windows).
- // By default, this value is based on the APIFY_HEADLESS environment variable.
- headless: Boolean,
-
- // URL of the proxy server, e.g. 'http://username:[email protected]:55555'.
- // Currently only the 'http' proxy type is supported.
- // By default it is null, which means no proxy server is used.
- proxyUrl: String,
-
- // Overrides the User-Agent HTTP header of the web browser.
- // By default it is null, which means the browser uses its default User-Agent.
- userAgent: String,
-}
-```
-
-The result of the `Apify.browse()` is a new instance of the `Browser` class,
-which represents a web browser instance (possibly with multiple windows or tabs).
-
-The `Browser` class has the following properties:
-
-```javascript
-{
- // An instance of the Selenium's WebDriver class.
- webDriver: Object,
-
- // A method that closes the web browser and releases associated resources.
- // The method has no arguments and returns a promise that resolves when the browser was closed.
- close: Function,
-}
-```
-
-The `webDriver` property can be used to manipulate the web browser:
-
-```javascript
-const url = await browser.webDriver.getCurrentUrl();
-```
-
-For more information, see [WebDriver documentation](http://seleniumhq.github.io/selenium/docs/api/
-javascript/module/selenium-webdriver/index_exports_WebDriver.html).
-
-When the web browser is no longer needed, it should be closed:
-
-```javascript
-await browser.close();
-```
- */
-
-// TODO: browse() is only kept for backwards compatibility, get rid of it after no actors are using it!
-
-/**
- * Opens a new web browser, which is attached to Apify 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 {String} [url] start URL to open. Defaults to about:blank
- * @param {Object} [options] settings, their defaults are provided by the getDefaultBrowseOptions() function.
- * @returns {Promise}
- *
- * @memberof module:Apify
- * @function
- * @ignore
- */
-export const browse = (url, options) => {
- const args = processBrowseArgs(url, options);
- const browser = new Browser(args.options);
-
- return browser._initialize() // eslint-disable-line no-underscore-dangle
- .then(() => {
- return browser.webDriver.get(args.options.url);
- })
- .then(() => {
- return browser;
- });
-};
-
-/**
- * Opens a new instance of Chrome web browser
- * controlled by <a href="http://www.seleniumhq.org/projects/webdriver/" target="_blank">Selenium WebDriver</a>.
- * The result of the function is the new instance of the
- * <a href="http://seleniumhq.github.io/selenium/docs/api/javascript/module/selenium-webdriver/index_exports_WebDriver.html" target="_blank">
- * WebDriver</a>
- * class.
- *
- * To use this function, you need to have Google Chrome and
- * <a href="https://sites.google.com/a/chromium.org/chromedriver/" target="_blank">ChromeDriver</a> installed in your environment.
- * For example, you can use the `apify/actor-node-chrome` base Docker image for your actor - see
- * <a href="https://apify.com/docs/actor#base-images" target="_blank">documentation</a>
- * for more details.
- *
- * For an example of usage, see the <a href="https://apify.com/apify/example-selenium" target="_blank">apify/example-selenium</a> actor.
- *
- * @param {Object} [options] Optional settings passed to WebDriver. Additionally the object can contain the following fields:
- * @param {String} [options.proxyUrl] - URL to a proxy server. Currently only `http://` scheme is supported.
- * Port number must be specified. For example, `http://example.com:1234`.
- * @param {String} [options.headless] - Indicates that the browser will be started in headless mode.
- * If the option is not defined, and the `APIFY_HEADLESS` environment variable has value `1`
- * and `APIFY_XVFB` is NOT `1`, the value defaults to `true`, otherwise it will be `false`.
- * @param {String} [options.userAgent] - User-Agent for the browser.
- * If not provided, the function sets it to a reasonable default.
- * @returns {Promise}
- *
- * @memberof module:Apify
- * @name launchWebDriver
- * @function
- */
-export const launchWebDriver = (options) => {
- const args = processBrowseArgs(undefined, options);
- const browser = new Browser(args.options);
-
- // NOTE: eventually get rid of the Browser class
- return browser._initialize() // eslint-disable-line no-underscore-dangle
- .then(() => {
- // TODO: for some reason this doesn't work, the proxy chain will never shut down!!
- // BTW this also prevents us from upgrading to mocha 4+
- // we'll need to find a way to fix this!
- // browser.webDriver.onQuit_ = () => {
- // if (browser.proxyChain) {
- // browser.proxyChain.shutdown();
- // browser.proxyChain = null;
- // }
- // };
-
- return browser.webDriver;
- });
-};
-
-// /**
-// * 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.
-// * @returns {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/test/puppeteer.js b/test/puppeteer.js
index 696920e8e..9692eeba9 100644
--- a/test/puppeteer.js
+++ b/test/puppeteer.js
@@ -164,31 +164,31 @@ describe('Apify.launchPuppeteer()', () => {
});
it('supports useChrome option', async () => {
- const mock = sinon.mock(utils);
- mock.expects('getTypicalChromeExecutablePath').once();
+ const spy = sinon.spy(utils, 'getTypicalChromeExecutablePath');
let browser;
const opts = {
useChrome: true,
headless: true,
};
+
try {
- await Apify.launchPuppeteer(opts)
- .then((result) => {
- browser = result;
- })
- .then(() => {
- return browser.newPage();
- })
- .then((page) => {
- return page.content();
- })
- .then(() => {
- return browser.close();
- });
+ browser = await Apify.launchPuppeteer(opts);
+ const page = await browser.newPage();
+
+ // Add a test to go to an actual domain because we've seen issues
+ // where pages would not load at all with Chrome.
+ await page.goto('https://example.com');
+ const title = await page.title();
+ const version = await browser.version();
+
+ expect(title).to.be.eql('Example Domain');
+ expect(version).to.include('Chrome');
+ expect(version).not.to.include('Chromium');
+ expect(spy.calledOnce).to.be.eql(true);
} finally {
- mock.verify();
- mock.restore();
+ spy.restore();
+ if (browser) await browser.close();
}
});
diff --git a/test/webdriver.js b/test/webdriver.js
deleted file mode 100644
index da76d7a72..000000000
--- a/test/webdriver.js
+++ /dev/null
@@ -1,520 +0,0 @@
-import _ from 'underscore';
-import { expect, assert } from 'chai';
-import proxy from 'proxy';
-import http from 'http';
-import util from 'util';
-import portastic from 'portastic';
-import basicAuthParser from 'basic-auth-parser';
-// import fs from 'fs';
-
-import { processBrowseArgs, getDefaultBrowseOptions } from '../build/webdriver';
-import Apify from '../build/index';
-
-/* globals process */
-
-let proxyServer;
-let proxyPort; // eslint-disable-line no-unused-vars
-const proxyAuth = { scheme: 'Basic', username: 'username', password: 'password' };
-let wasProxyCalled = false; // eslint-disable-line no-unused-vars
-
-// Setup local proxy server for the tests
-before(() => {
- // Find free port for the proxy
- return portastic.find({ min: 50000, max: 50100 }).then((ports) => {
- return new Promise((resolve, reject) => {
- const httpServer = http.createServer();
-
- // Setup proxy authorization
- httpServer.authenticate = function (req, fn) {
- // parse the "Proxy-Authorization" header
- const auth = req.headers['proxy-authorization'];
- if (!auth) {
- // optimization: don't invoke the child process if no
- // "Proxy-Authorization" header was given
- // console.log('not Proxy-Authorization');
- return fn(null, false);
- }
- const parsed = basicAuthParser(auth);
- const isEqual = _.isEqual(parsed, proxyAuth);
- // console.log('parsed "Proxy-Authorization": %j - %s', parsed, isEqual);
- if (isEqual) wasProxyCalled = true;
- fn(null, isEqual);
- };
-
- httpServer.on('error', reject);
-
- proxyServer = proxy(httpServer);
- proxyServer.listen(ports[0], () => {
- proxyPort = proxyServer.address().port;
- resolve();
- });
- });
- });
-});
-
-after(function () {
- this.timeout(30 * 1000);
- if (proxyServer) return util.promisify(proxyServer.close).bind(proxyServer)();
-});
-
-describe('getDefaultBrowseOptions()', () => {
- it('it works', () => {
- process.env.APIFY_HEADLESS = '1';
- const opts1 = getDefaultBrowseOptions();
- expect(opts1).to.eql({
- browserName: 'chrome',
- headless: true,
- proxyUrl: null,
- userAgent: null,
- });
-
- delete process.env.APIFY_HEADLESS;
- const opts2 = getDefaultBrowseOptions();
- expect(opts2).to.eql({
- browserName: 'chrome',
- headless: false,
- proxyUrl: null,
- userAgent: null,
- });
- });
-});
-
-describe('processBrowseArgs()', () => {
- it('it handles default parameters well', () => {
- expect(processBrowseArgs()).to.eql({
- options: {
- url: 'about:blank',
- },
- });
-
- expect(processBrowseArgs('example.com', { opt: true })).to.eql({
- options: {
- url: 'example.com',
- opt: true,
- },
- });
-
- expect(processBrowseArgs('example.com', { url: 'another.com' })).to.eql({
- options: {
- url: 'example.com',
- },
- });
-
- expect(processBrowseArgs('example.com')).to.eql({
- options: {
- url: 'example.com',
- },
- });
-
- expect(processBrowseArgs({})).to.eql({
- options: {
- url: 'about:blank',
- },
- });
-
- expect(processBrowseArgs({ url: 'example.com' })).to.eql({
- options: {
- url: 'example.com',
- },
- });
-
- expect(processBrowseArgs({ url: 'example.com' })).to.eql({
- options: {
- url: 'example.com',
- },
- });
-
- expect(processBrowseArgs({ some: 123 })).to.eql({
- options: {
- url: 'about:blank',
- some: 123,
- },
- });
- });
-});
-
-
-describe('Apify.launchWebDriver()', function () {
- // Need a large timeout to run unit tests on Travis CI
- this.timeout(30 * 1000);
-
- it('throws on invalid args', () => {
- assert.throws(() => {
- Apify.launchWebDriver({ proxyUrl: 'invalidurl' });
- }, Error);
- assert.throws(() => {
- Apify.launchWebDriver({ proxyUrl: 'http://host-without-port' });
- }, Error);
- assert.throws(() => {
- Apify.launchWebDriver({ proxyUrl: 'invalid://somehost:1234' });
- }, Error);
- });
-
- it('starts with no args', () => {
- process.env.APIFY_HEADLESS = '1';
- let webDriver;
- return Apify.launchWebDriver()
- .then((res) => {
- webDriver = res;
- expect(webDriver.constructor.name).to.eql('Driver');
- return webDriver.quit();
- });
- });
-
- it('opens https://www.example.com in headless mode', () => {
- delete process.env.APIFY_HEADLESS;
- let webDriver;
- return Apify.launchWebDriver({ headless: true })
- .then((res) => {
- webDriver = res;
- return webDriver.get('https://www.example.com');
- })
- .then(() => {
- expect(webDriver.constructor.name).to.eql('Driver');
- return webDriver.getCurrentUrl();
- })
- .then((url) => {
- expect(url).to.eql('https://www.example.com/');
- return webDriver.quit();
- });
- });
-
- it('works with proxy server', () => {
- let webDriver;
- wasProxyCalled = false;
- const opts = {
- headless: true,
- proxyUrl: `http://${proxyAuth.username}:${proxyAuth.password}@127.0.0.1:${proxyPort}`,
- };
- return Apify.launchWebDriver(opts)
- .then((result) => {
- webDriver = result;
- return webDriver.get('https://www.example.com');
- })
- .then(() => {
- // return webDriver.sleep(300 * 1000);
- })
- .then(() => {
- return webDriver.getAllWindowHandles();
- })
- .then(() => {
- expect(webDriver.constructor.name).to.eql('Driver');
- return webDriver.getCurrentUrl();
- })
- .then((url) => {
- expect(wasProxyCalled).to.equal(true);
- expect(url).to.eql('https://www.example.com/');
- return webDriver.quit();
- });
- });
-
- it('userAgent option works', () => {
- let webDriver;
- const opts = {
- headless: true,
- userAgent: 'MyUserAgent/1234 AnotherString/456',
- };
- return Apify.launchWebDriver(opts)
- .then((result) => {
- webDriver = result;
- return webDriver.get('https://api.apify.com/v2/browser-info');
- })
- .then(() => {
- expect(webDriver.constructor.name).to.eql('Driver');
- return webDriver.getPageSource();
- })
- .then((source) => {
- expect(source).to.contain(`"user-agent": "${opts.userAgent}"`);
- return webDriver.quit();
- });
- });
-});
-
-
-describe('Apify.browse()', function () {
- // Need a large timeout to run unit tests on Travis CI
- this.timeout(30 * 1000);
-
- it('throws on invalid args', () => {
- assert.throws(() => {
- Apify.browse('http://www.blabla.bla', { proxyUrl: 'invalidurl' });
- }, Error);
- assert.throws(() => {
- Apify.browse('http://www.blabla.bla', { proxyUrl: 'http://host-without-port' });
- }, Error);
- assert.throws(() => {
- Apify.browse('http://www.blabla.bla', { proxyUrl: 'invalid://somehost:1234' });
- }, Error);
- });
-
- it('opens about:blank with no args', () => {
- process.env.APIFY_HEADLESS = '1';
- let browser;
- return Apify.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();
- });
- });
-
- it('opens https://www.example.com in headless mode', () => {
- delete process.env.APIFY_HEADLESS;
- let browser;
- return Apify.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();
- });
- });
-
- it('works with proxy server', () => {
- let browser;
- wasProxyCalled = false;
- const opts = {
- url: 'https://www.example.com',
- headless: true,
- browserName: 'chrome',
- proxyUrl: `http://${proxyAuth.username}:${proxyAuth.password}@127.0.0.1:${proxyPort}`,
- };
- return Apify.browse(opts)
- .then((result) => {
- browser = result;
- })
- .then(() => {
- // return browser.webDriver.sleep(300 * 1000);
- })
- .then(() => {
- return browser.webDriver.getAllWindowHandles();
- })
- .then(() => {
- expect(browser.constructor.name).to.eql('Browser');
- return browser.webDriver.getCurrentUrl();
- })
- .then((url) => {
- expect(wasProxyCalled).to.equal(true);
- expect(url).to.eql('https://www.example.com/');
- return browser.close();
- });
- });
-
- it('userAgent option works', () => {
- let browser;
- const opts = {
- url: 'https://api.apify.com/v2/browser-info',
- headless: true,
- browserName: 'chrome',
- // Have space in user-agent to test passing of params
- userAgent: 'MyUserAgent/1234 AnotherString/456',
- };
- return Apify.browse(opts)
- .then((result) => {
- browser = result;
- })
- .then(() => {
- expect(browser.constructor.name).to.eql('Browser');
- return browser.webDriver.getPageSource();
- })
- .then((source) => {
- expect(source).to.contain(`"user-agent": "${opts.userAgent}"`);
- return browser.close();
- });
- });
-
-/*
- it('test cache dir', () => {
- console.log('HEREE');
- let browser;
- const opts = {
- url: 'https://apify.com/',
- headless: false,
- browserName: 'chrome',
- extraChromeArguments: ['--disk-cache-dir=/Users/jan/Projects/apify-runtime-js/_profiles/xxx1'], //, '--disk-cache-size=10000000'],
- };
- Apify.setPromisesDependency(Promise);
- return Apify.browse(opts)
- .then((result) => {
- browser = result;
- })
- .then(() => {
- // return browser.webDriver.sleep(300 * 1000);
- })
- .finally(() => {
- // return browser.close();
- });
- });
-
- it('test xxx', () => {
- // const _ = require('underscore');
- // const Apify = require('apify');
- // const request = require('request-promise');
-
-
- console.log('Starting');
-
- let browser;
-
- return Apify.browse({
- url: 'https://www.momondo.co.uk/flightsearch/?Search=true&TripType=2&SegNo=2&SO0=LHR&SD0=SGN&SDP0=
- 11-10-2017&SO1=SGN&SD1=LHR&SDP1=18-10-2017&AD=1&TK=ECO&DO=false&NA=false',
- //url: 'http://www.example.com',
- userAgent: 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_5) AppleWebKit/537.36 (KHTML, like Gecko)
- Chrome/60.0.3112.32 Safari/537.36',
- proxyUrl: 'http://something.com',
- headless: true,
- //extraChromeArguments: ['--reduce-security-for-testing', '--disable-web-security'],
- })
- .then((result) => {
- browser = result;
- return browser.webDriver.sleep(10000);
- })
- .then(() => {
- return browser.webDriver.takeScreenshot();
- })
- .then((screenshotBase64) => {
- const buffer = Buffer.from(screenshotBase64, 'base64');
- fs.writeFileSync('/Users/jan/Projects/apify-runtime-js/xxxx.png', buffer);
-
- return new Promise(() => {});
- });
-
- /*
- browser.webDriver.sleep(5000);
-
- const url = await
- browser.webDriver.getCurrentUrl();
- console.log(`Browser opened (URL: ${url})`);
-
- // Inject Weinre
- const injectJs = '(function(e){e.setAttribute("src","http://139.162.172.178:8080/target/target
- -script-min.js#anonymous");document.getElementsByTagName("body")[0].appendChild(e);})(document
- .createElement("script"));void(0);';
- await
- browser.webDriver.executeScript(injectJs);
-
- const condition = async () => {
- const text = await browser.webDriver.executeScript(
- 'return (document.getElementById("searchProgressText") || {}).innerText');
- const html = await browser.webDriver.executeScript('return document.documentElement.innerHTML');
- console.log(`Search text: ${text} (HTML size: ${html.length})`);
- return text === 'Search complete';
- };
- const found = await
- browser.webDriver.wait(condition, 60 * 1000);
-
- if (found) {
- console.log('Wohooo, search complete!');
- } else {
- console.log('Timed out!');
- }
- }); */
-});
-
-
-// These tests don't work on Travis CI, we don't need launchChrome() anyway
-// describe('launchChrome()', function () {
-// // Need a large timeout to run unit tests on Travis CI
-// this.timeout(300 * 1000);
-//
-// let launcher;
-//
-// before(() => {
-// process.env.APIFY_HEADLESS = '1';
-// return launchChrome().then((l) => {
-// launcher = l;
-// });
-// });
-//
-// it('reports headless browser 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);
-// });
-// });
-//
-// // 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(() => {
-// if (launcher) return launcher.kill();
-// });
-// });