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
Add getRandomUserAgent() to public utils
Ondra Urbanb19c913a57ec
diff --git a/src/utils.js b/src/utils.jsindex 673289b8c..486424859 100644--- a/src/utils.js+++ b/src/utils.js@@ -9,9 +9,9 @@ import pidusage from 'pidusage';import requestPromise from 'request-promise';import _ from 'underscore';import XRegExp from 'xregexp';-import { delayPromise } from 'apify-shared/utilities';+import { delayPromise, getRandomInt } from 'apify-shared/utilities';import { checkParamOrThrow } from 'apify-client/build/utils';-import { ENV_VARS } from './constants';+import { ENV_VARS, USER_AGENT_LIST } from './constants';export const PID_USAGE_NOT_FOUND_ERROR = 'No maching pid found';@@ -376,6 +376,14 @@ const extractUrls = ({ string, urlRegExp = URL_NO_COMMAS_REGEX }) => {return string.match(urlRegExp) || [];};+/**+ * Returns a randomly selected User-Agent header out of a list of the most common headers.+ */+const getRandomUserAgent = () => {+ const index = getRandomInt(USER_AGENT_LIST.length);+ return USER_AGENT_LIST[index];+};+/*** A namespace that contains various utilities.*@@ -394,6 +402,7 @@ export const publicUtils = {sleep,downloadListOfUrls,extractUrls,+ getRandomUserAgent,URL_NO_COMMAS_REGEX,URL_WITH_COMMAS_REGEX,};diff --git a/test/utils.js b/test/utils.jsindex 821142754..31d2e4630 100644--- a/test/utils.js+++ b/test/utils.js@@ -519,3 +519,11 @@ describe('Apify.utils.downloadListOfUrls()', () => {})).to.eventually.deep.equal(arr);});});++describe('Apify.utils.getRandomUserAgent()', () => {+ it('works', () => {+ const agent = utils.publicUtils.getRandomUserAgent();+ expect(agent).to.be.a('string');+ expect(agent.length).to.not.be.eql(0);+ });+});