Great Learning Guide of Puppeteer Browser Class (Tutorial 8)

Puppeteer is an open-source node js library and is used a web automation as well as web scraping tool. You need the basic understanding of Javascript, and HTML DOM structure to start working with Puppeteer. This Puppeteer tutorial series is distributed in the below segments which will equip you with all the necessary experience to start working with Puppeteer. 

Puppeteer Tutorial

Tosca Tutorial #1: Puppeteer Overview

Tosca Tutorial #2: Puppeteer Environment Variables

Tosca Tutorial #3: Puppeteer Web Scraping and Puppeteer Test Automation Overview

Tosca Tutorial #4: Install Puppeteer

Tosca Tutorial #5: Sample Puppeteer Project

Tosca Tutorial #6: Puppeteer Automation Testing

Tosca Tutorial #7: Puppeteer Class

Tosca Tutorial #8: Puppeteer Browser Class

Tosca Tutorial #9: Puppeteer Page Class

In this “Puppeteer Browser Class” tutorial, we will have in depth understanding further about the below mentioned classes which consists of the important namespaces, events, and other exhaustive methods that are needed to work with Puppeteer web scraping techniques.  

Puppeteer BrowserFetcher Class

Puppeteer BrowserFetcher Class is used to download and manage the different browser versions. BrowserFetcher class operates on a revision string that specifies the version of the chrome browser. The revision number can be obtained from here. In the case of Firefox, it downloads the browser nightly based on the version number.

Below example shows how to download and launch the chrome browser using BrowserFetcher class.

const browserFetcher = puppeteer.createBrowserFetcher();
const revInfo = await browserFetcher.download('766890');
const browserChrome= await puppeteer.launch({executablePath: revInfo.executablePath})

It is not possible to work simultaneously with another instance of BrowserFetcher class. The frequently used methods of BrowserFetcher class are explained in the next sections.

Puppeteer BrowserFetcher Class – Methods:

Below methods are available in puppeteer browserfetcher class,

browserFetcher.canDownload(revision) – With the help of the revision number of the browser, this method checks the availability of the specified browser as a part of the header request. The method returns the boolean value(true or false) based on availability.

const boolVar = browserFetcher.canDownload(‘766890’);

browserFetcher.download(revision[, progressCallback]) – This method downloads the chrome browser using the revision number argument. Here progressCallback is an optional argument that calls the function with two arguments – downloaded bytes and total bytes. This method returns the revision information as a promise object.

const revInfo = browserFetcher.download(‘766890’);

browserFetcher.host() – It returns the hostname, which is used for downloading of browser.

const hostName = browserFetcher.host();

browserFetcher.localRevisions() – It returns the list of all revisions which are available in the local system.

const revList = browserFetcher.localRevisions();

browserFetcher.platform() – It returns the platform name of the host, which will be any of the mac, Linux, win32, or win64.

const platformName = browserFetcher.platform();

browserFetcher.product() – It returns the browser name which will be either chrome or firefox

const productName = browserFetcher.product();

browserFetcher.remove(revision) – This method is used to remove the specified revision for the current product/browser. It returns the promise object, which is resolved after completion of the process.

const revInfo = browserFetcher.remove(‘766890’);

browserFetcher.revisionInfo(revision) – It will return an object on revision information which includes revision, folderPath, executablePath, url, local, and product.

const revInfo = browserFetcher.revisionInfo(‘766890’);

Reference: Click here to learn more on BrowserFetcher Class methods.

Puppeteer Browser Class

The Puppeteer Browser class is created when the puppeteer launched or connected the browser using puppeteer.launch or puppeteer.connect methods.

Below example shows how to create the Browser class and Page using the browser reference.

const puppeteer = require('puppeteer');
(async () => {
  const browserChrome = await puppeteer.launch();
  const pageChrome = await browserChrome.newPage();
  await pageChrome.goto('https://www.google.com');
  await browserChrome.close();
})();

The frequently used events and methods of Browser class are explained in the next section.

Puppeteer Browser Class – Events:

Below events are available in browser class,

  • browser.on(‘disconnected’) – This event is triggered when the browser is closed/crashed or browser.disconnect method is called.
  • browser.on(‘targetchanged’) – This event is triggered when the url of the target has changed.
  • browser.on(‘targetcreated’) – This event is triggered when the new page opened in a new tab or window by the method browser.newPage or window.open.
  • browser.on(‘targetdestroyed’) – This event is triggered when the target is destroyed, i.e., the page is closed.

Puppeteer Browser Class – Methods:

Below methods are available in browser class,

  • browser.browserContexts() – It returns the list of all browser contexts. For a newly launched browser, this method will return the single BrowserContext instance.
  • browser.close() – This method is used to close all the open chromium-browser pages. 

await browser.close();

  • browser.createIncognitoBrowserContext() – It creates/returns the incognito browser context, which will never share the cookies or cache with any other browser contexts. In the below example, the web page(google) will be opened in incognito mode.

(async () => {
  const chromeBrowser = await puppeteer.launch();
  // Create new incognito browser context.
  const context = await chromeBrowser.createIncognitoBrowserContext();
  const pageChrome = await context.newPage();
  await pageChrome.goto(‘https://www.google.com’);
})();

  • browser.defaultBrowserContext() – It returns default browser context which can not be destroyed or closed.
  • browser.disconnect() – It will disconnect the browser from the puppeteer. But, the browser will remain running in this case.
  • browser.isConnected() – This method checks if the browser is connected or not. It will return boolean values based on the check.

const boolFlag = await browser.isConnected();

  • browser.newPage() – This method will create a new page and return the instance of the page.

const page = await browser.newPage();

  • browser.pages() – This method returns the list of all pages which are currently in the open state.

const pageList = await browser.pages();

  • browser.process() – This method returns the created browser process. If the browser is created using browser.connect method, and it will return a null value.
  • browser.target() – This method returns the target associated with the browser.

const target = await browser.target();

  • browser.targets() – It returns the list of all active targets within the browser.

const targetList = await browser.targets();

  • browser.userAgent() – It returns the promise object about the original agent of the browser.
  • browser.version() – It returns the version of the browser in the format of ‘HeadlessChrome/xx.x.xxxx.x’ for headless chrome and ‘Chrome/xx.x.xxxx.x’ for non headless chrome. The format can change in a future release.
  • browser.waitForTarget(predicate[, options]) – It will search in all the browser contexts and wait for the target.

await pageChrome.evaluate(() => window.open(‘https://techiescience.com/’));
const newWindowTarget = await browser.waitForTarget(target => target.url() === ‘https://techiescience.com/’);

  • browser.wsEndpoint() – It returns the web socket url of the browser.

const wsUrl = await browser.wsEndPoint();

Reference: Click here to learn more on Browser class events and methods.

Puppeteer BrowserContext Class

The BrowserContext class helps to operate multiple browser instances. After launching a browser instance, by default, a single BrowserContext is used. The browserChrome.newPage() method creates a page in the default BrowserContext class object. If a web page invokes another page, then the new page should belong to the browsercontext of the parent page. Here, the new page can be created using the window.open() method. 

In the below example, Puppeteer has the ability to create a browser context in ‘incognito’ mode. The ‘incognito’ browser context does not write any data in the storage.

// Incognito browser context creation
const contextIncognito = await browserChrome.createIncognitoBrowserContext();
// New page creation through the browser context.
const pageChrome = await contextIncognito.newPage();
await pageChrome.goto('https://www.google.com');
//close context after use
await contextIncognito.close();

The frequently used events and methods of BrowserContext class are explained in the next section.

Puppeteer BrowserContext Class – Events:

Below events are available in browsercontext class,

  • browserContext.on(targetchanged) – This event is triggered when the url of the target within the browser context has changed.
  • browserContext.on(targetcreated) – This event is triggered after creation of  inside the browser context. The methods window.open and browserContext.newPage are responsible for this event.
  • browserContext.on(‘targetdestroyed’) – This event is triggered when the target is destroyed within the browser context.

Puppeteer BrowserContext Class – Methods:

Below methods are available in browsercontext class,

  • browserContext.browser() – This method returns the browser object which is available within the browser context.
  • browserContext.clearPermissionOverrides() – This method removes all permission overrides from the browser context. The below example shows how to use this method – 

const browserContext = browser.defaultBrowserContext();
browserContext.overridePermissions(‘https://www.google.com’, [‘clipboard-read’]);
browserContext.clearPermissionOverrides();

  • browserContext.close() – This method is used to close or destroy the browser context. All the browsers available within the browser context will be closed.

browserContext.close();

  • browserContext.isIncognito() – This method is used to check if the browser has been created in ‘incognito’ mode or not. It returns a boolean value(true – incognito mode or false – non-incognito mode) based on the browser mode. By default, any browser is invoked in ‘non-incognito’ mode.

const boolIsIncognito = browserContext.isIncognito();

  • browserContext.newPage() – This method is used to create a new page in the same browsercontext.

browserContext.newPage();

  • browserContext.overridePermissions(origin, permission) – This method is used to grant the specified permission to the origin, i.e., the target url. The different permissions which are available to grant are –
  • ‘geolocation’
  • ‘midi-sysex’ (system-exclusive midi)
  • ‘midi’
  • ‘push’
  • ‘camera’
  • ‘notifications’
  • ‘microphone’
  • ‘ambient-light-sensor’
  • ‘accelerometer’
  • ‘background-sync’
  • ‘gyroscope’
  • ‘accessibility-events’
  • ‘clipboard-read’
  • ‘magnetometer’
  • ‘clipboard-write’
  • ‘payment-handler’

The below example shows how to grant permission –

const browserContext = browser.defaultBrowserContext();
await browserContext.overridePermissions(‘https://www.google.com’, [‘geolocation’]);

  • browserContext.pages() – This method returns the list of all the open pages available in the browser context. Any non-visible page will not be listed here.

const openPageList = browserContext.pages();

  • browserContext.targets() – This method returns the list of all the active targets available in the browser context. Any non-visible page will not be listed here.

const activeTargetList = browserContext.targets();

  • browserContext.waitForTarget(predicate[, options]) – This method is used to wait for a target to have appeared and returned the target object. The argument, ‘predicate’ is basically a function call for each of the targets. Also, optionally, we can pass some configuration values such as timeout as a second argument.
await pageChrome.evaluate(() => window.open('https://www.google.com/'));
const newWindowTarget = await browserContext.waitForTarget(target => target.url() === 'https://www.google.com/');

Reference: Click here to read more on BrowserContext class events and methods.

Conclusion:

In this “Puppeteer Browser Class” tutorial, we have explained the BrowserFetcher class, BrowserContext class, and Browser class which includes the important namespaces(if any), events(if any), and methods that are frequently used in Puppeteer web scraping techniques with examples. In the next article, we will explain Page, Frame, and Dialog class.

Great Learning Guide of Puppeteer Class (Tutorial 7)

Puppeteer which is an open-source node js library, can be used as a web scraping tool. Understanding of command line, Javascript, and HTML DOM structure should be good to start with this puppeteer tutorial. The Series of Puppeteer tutorial is distributed among below Sub section to get a good hold on Puppeteer. 

Puppeteer Tutorial

Puppeteer Tutorial #1: Puppeteer Overview

Puppeteer Tutorial #2: Puppeteer Environment Variables

Puppeteer Tutorial #3: Puppeteer Web Scraping and Puppeteer Test Automation Overview

Puppeteer Tutorial #4: Install Puppeteer

Puppeteer Tutorial #5: Sample Puppeteer Project

Puppeteer Tutorial #6: Puppeteer Automation Testing

Puppeteer Tutorial #7: Puppeteer Class

Puppeteer Tutorial #8: Puppeteer Browser Class

Puppeteer Tutorial #9: Puppeteer Page Class

In this “Puppeteer Class” tutorial, we will explain the below classes which include the important namespaces(if any), events(if any), and methods which are frequently used in Puppeteer web scraping techniques. 

We will explain important components with examples throughout this article.  

Puppeteer Class

Conceptually, the class is a blueprint of an object which defines a set of instructions( variables and methods). Here, the Puppeteer class is defined using javascript to perform different actions to perform web scraping. Let’s check the below example, the Puppeteer class module has been used to launch a Chromium web instance.

const puppeteer = require('puppeteer');
(async () => {
  const browserChrome = await puppeteer.launch();
  const pageChrome = await browserChrome.newPage();
  await pageChrome.goto('https://www.google.com');
  // We can write steps here
  await browserChrome.close();
})();

Puppeteer class also provides multiple Namespaces and Methods, which supports the web scraping process. The frequently used Namespaces and Methods are explained next sections.

Puppeteer Class – Namespaces:

It’s a container that defines multiple identifiers, methods, variables, etc., in javascript. It’s a way to group the code in a logical and organized way. Below namespaces are provided by the Puppeteer class.

puppeteer.devices: It returns a list of devices that can be used by the method page.emulate(options) to perform scraping in mobile devices. 

Example – Open and close google web page on a mobile device –

const puppeteer = require('puppeteer');
const samsung = puppeteer.devices['Samsung J5'];
(async () => {
  const browserChrome = await puppeteer.launch();
  const pageChrome = await browserChrome.newPage();
  await pageChrome.emulate(samsung);
  await pageChrome.goto('https://www.google.com'); 
  await browserChrome.close();
})();

puppeteer.errors: While working with different puppeteer methods, there is a chance of exceptions. Mostly, if the methods are unable to fulfill the requests, it throws errors. There are different classes defined to handle errors through the ‘puppeteer.errors’ namespace.

Example – for method page.waitForSelector, if the web element does not appear within the specified time, then the timeout error will appear. Please go through the below example, which shows an approach to handle timeout,

try {
  await page.waitForSelector('<web-element>');
} catch (err) {
  if (err instanceof puppeteer.errors.TimeoutError) {
    // Write code to handle the timeout error.
  }
} 

puppeteer.networkConditions: It returns a list of network conditions that can be used on the method page.emulateNetworkConditions(networkConditions). The complete list of network conditions is defined here.

Example – Through this code sample, we will open the google web page using a pre-defined network condition.

const puppeteer = require('puppeteer');
const net = puppeteer.networkConditions['Fast 3G'];
(async () => {
  const browserChrome = await puppeteer.launch();
  const pageChrome = await browserChrome.newPage();
  await pageChrome.emulateNetworkConditions(net);
  await pageChrome.goto('https://www.google.com');
  await browserChrome.close();
})();

puppeteer.product: It returns the name of the browser, which will be used for automation(Chrome or Firefox). The product for the browser is set by either environment variable PUPPETEER_PRODUCT or the product option available in puppeteer class method puppeteer.launch([options]). The default value is Chrome.

Reference: Click here to learn more on Puppeteer Class namespaces.

Puppeteer Class – Methods:

Methods contain statements to perform the specific action. The puppeteer class have below methods,

puppeteer.clearCustomQueryHandlers() – It clears all registered handlers.

puppeteer.connect(options) – This method is used to connect puppeteer with any existing browsers. It returns an object of type promise which indicates the status of this asynchronous process. Example – In the below example, puppeteer disconnect from the current browser and reconnect,

const puppeteer = require('puppeteer');
(async () => {
  const browserChrome = await puppeteer.launch();
  // Copy the endpoint reference which will be reconnected later
  const endpoint = browserChrome.wsEndpoint();
  // Disconnect puppeteer
  browserChrome.disconnect();
  // Use the endpoint to re-connect
  const browserChrome2 = await puppeteer.connect({endpoint});
  // Close second instance of Chromium
  await browserChrome2.close();
})();

puppeteer.createBrowserFetcher([options]) – It creates a browser fetcher object to download and manage the different versions of browsers (Chrome and Firefox).

const browserFetcher = puppeteer.createBrowserFetcher();

puppeteer.customQueryHandlerNames() – It returns an array of all the registered custom query handlers.

puppeteer.defaultArgs([options]) – It returns the default configuration options of chrome browser as an array while launching. Also, we can set the configurable options of a browser using the optional argument option.

const args = puppeteer.defaultArgs();

puppeteer.executablePath() – It returns the path is expected by the puppeteer for the bundled browser instance. The path that would not be available in the download was skipped by the environment variable PUPPETEER_SKIP_DOWNLOAD. Also, we can use the environment variables PUPPETEER_EXECUTABLE_PATH and PUPPETEER_CHROMIUM_REVISION to change the path.

const args = puppeteer.executablePath();

puppeteer.launch([options]) – This puppeteer class method is used to launch the web browser. Through the optional argument, we can pass the different configurations of the browser, such as product(browser name), headless, devtools, etc. This method returns the promise object, which holds the reference of the launched browser.

const browser = await puppeteer.launch();

puppeteer.registerCustomQueryHandler(name, queryHandler) – It’s used to register a custom query handler. Here “name” provides the name of the query handler, and “queryHandler” defines the actual custom query handler.

puppeteer.unregisterCustomQueryHandler(name) – It’s used to unregister any custom query handler.

Reference: Click here to read more on Puppeteer Class methods.

Target Class

The target class provides methods to work with targets. The most frequently used methods which are available with target class are explained in the next section.

Target Class – Methods:

Below methods are available in targets class –

  • Target.browser() – It returns the browser object which is linked to the target.
  • Target.browserContext() – It returns an object of type browserContext which is linked to the target.
  • Target.createCDPSession() – It creates and returns the devtool protocol session of the chrome, which is attached to the target.
  • Target.opener() – It returns the target which opens this target. Basically, this method is used to get the parent target. It returns null for the top-level target.
  • Target.page() – It returns the page object of the target. If the type of the target is not a page, it returns a null value.
  • Target.type() – It’s used to get the type of the target. The return value can be either of the options – ’background_page’ , ‘page’ ,’shared_worker’,’service_worker’,’browser’ or ‘other’.
  • Target.url() – It returns the url of the target.
  • Target.worker() – It returns the webworker object. The return value is null if the target is neither ‘service_worker’ nor ‘shared_worker’.

Reference: Click here to read more on Target class methods.

ConsoleMessage Class

The ConsoleMessage class objects are dispatched by page through the console event. The frequently used methods of the consoleMessage class are explained in the next section.

ConsoleMessage Class – Methods:

Below methods are available in ConsoleMessage class –

  • consoleMessage.args() – It returns a array of JSHandler object. The JSHandler prevents the linked JS object from being garbage collected until the handle is disposed of. It’s automatically destroyed when the parent browser context is destroyed.
  • consoleMessage.location() – It returns an object of the resource, which includes the below parameters.
  • url – It denotes the URL of the known resource. If not known, it will keep an undefined value.
  • LineNumber – It’s the 0-based line number that is available in the resource. If not available, it will keep an undefined value.
  • columNumber – It’s the 0-based column number that is available in the resource. If not available, it will keep an undefined value.
  • consoleMessage.stackTrace() – It returns a list of objects(each object refers a resource) which includes below parameters.
  • url – It denotes the URL of the known resource. If not known, it will keep an undefined value.
  • LineNumber – It’s the 0-based line number that is available in the resource. If not available, it will keep an undefined value.
  • columNumber – It’s the 0-based column number that is available in the resource. If not available, it will keep an undefined value.
  • consoleMessage.text() – It returns the text of the console.
  •  consoleMessage.type() – It returns the string as the type of console message. The type can be either of the values – log, debug, info, error, warning, dir, dirxml, table, trace, clear, startGroup, startGroupCollapsed, endGroup, assert, profile, profileEnd, count, timeEnd.

Reference: Click here to learn more on consoleMessage class methods.

TimeoutError Class

While working with different puppeteer, there is a chance of exceptions. Mostly, if the methods are unable to fulfill the requests, it throws errors. The TimeoutError class is used to handle this kind of exception.

Example of TimeoutError Class – for method page.waitForSelector, if the web element does not appear within the specified time, then the timeout error will appear. Please go through the below example, which shows an approach to handle timeout,

try {
  await page.waitForSelector('<element>');
} catch (e) {
  if (e instanceof puppeteer.errors.TimeoutError) {
    // Write code to handle the error.
  }
} 

FileChooser Class

The file chooser class object is created using the method page.waitForFileChooser. The FileChooser class is used to interact with files. The frequently used methods of the FileChooser class are explained in the next section.

FileChooser Class – Methods:

Below methods are available for FileChooser class –

  • fileChooser.accept(file_with_path) – This method is used to upload any file (for which path is provided as an argument).
  • fileChooser.cancel() – This method is used to cancel the file upload process.
  • fileChooser.isMultiple() – This method checks if the fileChooser allows to select multiple values. It returns a boolean expression(true or false).

An example of FileChooser class –

const [fileChooser] = await Promise.all([
  page.waitForFileChooser(),
  page.click('#attach-button'), 
]);
await fileChooser.accept(['/puppeteer_proj/data/sample_file.pdf']);

Conclusion:

In this “Puppeteer Class” tutorial, we have explained the Puppeteer class, Target class, MessageConsole class and TimeoutError class which includes the important namespaces(if any), events(if any), and methods that are frequently used in Puppeteer web scraping techniques with examples. In the next article, we will explain BrowserContext, Browser, and BrowserContext Class.

Tosca Automation Tool: An Excellent Learning Guide

Tosca Automation Tool Tosca Commander 300x179 1

Tosca Tutorial – Table of Content

Tosca Tutorial #1: Tosca Overview

Tosca Tutorial #2: Tosca Automation Overview

Tosca Tutorial #3: Tricentis Tosca Setup – Install, Uninstall and License Configuration

Tosca Tutorial #4: Tosca Workspace Creation

Tosca Tutorial #5: Understanding of TOSCA Commander and Tosca User Management

Tosca Tutorial #6: Tosca Scanning – An Introduction to Modules

Tosca Tutorial #7: Tosca Test Case Creation

Tosca Tutorial #8: Tosca Parameters and Library– Buffer, Business Parameter, TCP

Tosca Tutorial #9:Tosca Test Execution, Reports, and Bug management

Tosca Tutorial #10: Test Case Design – An approach to test data management 

Tosca Tutorial #11: Tosca Test Data Management.

Tosca Tutorial #12: API Testing in Tosca

Tosca Tutorial #13: Tosca Interview Questions and Answers

In this Tosca Tutorial, we will learn about overview of Tosca Automation Tool which includes –

  • Tosca Automation Tool
  • Tosca Workspace
  • Tosca Commander
  • Tosca Automation

Tosca Automation Tool

Being a test tool, Tosca has the ability to automate the functional and regression testing scenarios. It is also capable of mobile and API testing, which is now mandatory for any product delivery in AGILE mode. Tosca supports scripts less automation i.e., scripts and coding is not required to automate any scenario. So, anyone can learn the tool easily and start developing test cases.TOSCA supports its users to build efficient test cases in a methodologically way and provide detailed reports for management.

Tosca Key Features Are:

  • Model-Based Testing Approach: It’s one of the significant features of Tosca as a test automation tool. It helps Tosca to gain leverage over other automation tools. Tosca creates a model of AUT(application under test) to create the test case with out using of scripts.
  • Risk-Based Testing Approach: As per the name explains, this feature helps users to assess the risk with respect to test cases and allows them to identify the right set of test scripts to minimize the risks. Following different black box testing approaches such as boundary testing, equivalence partitioning, decision box, linear expansion, etc. are utilized to reduce the test script count by ensuring the functional risk coverage. After completion of test execution, risks are measured based on the test results and risk coverage.
  • Scriptless test cases: Tosca allows script less automation. It means test cases are created based on the modules which are added by drag and drop method, test data parameters, etc. after carefully incorporating the checkpoints. So, anybody can develop the test suite with minimum programming knowledge.
  • Dynamic test data: Test data can be stored separately in a central repository.
  • Easy to the maintenance of test cases:  In case of a change in application or data, it can be easily incorporated in the test suite by updating the centrally stored modules, library, and data.
  • Distribute Execution: Tosca also provides a great feature to schedule and execute the test cases in different distributed systems in an unattended mode. It reduces the human efforts for testing.
  • API Testing: Due to these features, we can test the applications which are partially developed through the API.
  • Test Recording: Linear test cases can be developed through recording mode with checkpoints to save time.
  • Detailed Reporting and execution logs: Tosca generates a detailed report with screenshots. Also, the report can be customized based on the requirements.
  • Mobile Testing: Tosca is also capable of mobile(android and ios) test automation without using any third-party tools.
  • Supports different kinds of applications: Tosca as a test automation tool, has the ability to automate most of the major applications such as Web, Salesforce, SAP, Powerbuilder, DotNet, android/ios devices, etc.
  • Ability to integrate with third-party tools: It also allows us to integrate with any third-party tools like ALM, Perfecto, Selenium, Azure, etc.

Tosca Commander

The Tosca commander is the primary component of Tricentis Tosca Automation tool. It has the capability to manage all the activities which are involved with test automation. It has five primary sections – 

1. Module Sections – This section contains all the standard and user-defined modules which are required to build the automated test cases.

2. Testcase Section – Technical components of test cases are stored here.

3. TestCaseDesign Section – Dynamic test data are stored here, which are used by the test cases.

4. Execution Section – All the test executions are performed from this section through execution lists. After the execution, detailed logs are kept here.

5. Requirements Section – Requirements related information are stored here.

The primary functions of the Tosca Commander are mentioned below – 

  • Tosca User management
  • Scan applications to create modules
  • Create a library
  • Create a test case
  • Test data parameterization using TCP, TCD, TDM, TDS
  • Maintenance of test cases
  • Test execution
Tosca Automation Tool - Tosca Commander
Tosca Automation Tool – Tosca Commander

Click here to read more on Tosca Commander.

Tosca Workspace

Tosca workspace is a place where any user can perform different activities such as test building, maintenance, execution etc. which are related to Tosca test automation. Workspace is created in the local drive. But it can also be created in a shared network drive or different databases as a central repository based on the business requirement. It is recommended that only one user should be assigned to a single workspace. 

For a multiuser environment, the workspace should be created in a central place which can be accessed by each of the users. 

In a Singleuser Workspace, only one user has access to the workspace. So, the managing of the data and sources is not required.

The Multiuser Workspace manages the data administration more simple as all data of a project are kept in a central location which is called Common Repository. So, in the multiuser workspace, the user has to check out(lock) the different components before modifying it to avoid any data loss. After finishing the update, the user has to check-in(unlock) the components to save the same in the common repository so that any other user can access it.

Pleas click here to learn Tosca Workspace in detailed exlanations.

Tosca Automation Tool - Tosca Workspace
Tosca Automation Tool – Tosca Workspace

Tosca Automation

We have to learn about below topics to understand the overview of Tosca Automation.

Tosca Modules:

The technical information of controls are stored in Tosca modules. The purpose of the technical information to steer the test objects.

To develop the test cases in Tosca, the first step is to scan the application and created the modules. We has to scan and create modules for all the required controls from each of the pages/screens of the test application. Each of the test objects which are available in application pages/ screens, are treated as “control” in Tosca. The controls which are required during test execution, has to be added as module’s attribute.

Two types of modules are available in Tricentis Tosca. Those are –

·        Classic Modules – It uses classic engines to steer the test objects.

·        XModules – On the other side, It uses TBox framework based Tosca XEngines.

Tosca Automation Tool - Tosca Modules
Tosca Automation Tool – Tosca Modules

Click here to learn more on Tosca Modules.

Tosca Test Case:

Test Case is a group of logical steps/ blocks of instructions to verify the specific functionality of an application under test(AUT). The Test Case can be either manual or automated. Through this article, we will explain about the automated Tosca test cases. Tosca Test Case is basically a combination of standard and user-defined modules with verification points.

Classification of Tosca Test Cases:

  • Technical Test Cases
  • Business Test Case

Technical Test Cases:

These are the physical Test Cases that are used to verify the test scenarios. It can be created after right-clicking on any folder available in the Test Cases section and selecting a circular arrow icon with blue color. There is a short cut keys are available to create Tosca test cases using the key combinations of “Ctrl+N” and “Ctrl+T.”  

Test Step: The test steps can be created by inserting (or drag -drop) the modules into the Test Cases. So, after adding the modules with actions and data in test case, are represented as test steps. After selecting the module or test step from the left panel, in the right side details section has appeared. Tosca Test Cases are supported below operations –

  • If-Else Condition
  • Condition
  • Looping Statements
  • Storage

Business Test Case:

Business Test Cases are used to create logical groups to define functional coverage. One business Test Case is a group of one or more technical Test Cases. We cannot execute it directly. It’s used only for monitoring the functional coverage of testing during the testing cycle.

Tosca Automation Tool - Tosca Test Case
Tosca Automation Tool – Tosca Test Case

Click here to learn more on test cases as a part to Tosca Automation.

Tosca Parameters:

Parameterization is an approach to feed test data through parameters or variables into the Test Cases. In this article, we will discuss parameters such as buffer and test configuration parameters.

Buffer – We can consider a variable as a Buffer in Tosca to store the data. The buffer scope is restricted to the local workspace. So, the buffer can not be accessed by any other test system as the buffer values are not updated to common repository.

Test Configuration Parameters – The shorter form of Test Configuration Parameters is TCP, which can be defined in the Test Case folder, Test Case, and execution list level. When the TCPs are defined in folder level, it can be access from all the child folders and test cases. The syntax for TCP to access the value is {CP[<logical name>]}. We can create, modify or view the TCPs from the Test Configuration section of any test case, folder, or execution list.

The configuration or test environment related data, which are unique for entire test suites, should be kept in test configuration parameters (TCPs) . The examples of the advisable TCP parameters are such as path of the application, URL, environment name, user details, reporting path, etc.

Tosca Library:

Test Step Block – It is a collection of test steps which is required to automate a small functionalities. Conceptually, it is the same as function or method. The logical grouping is done through Test Case level folders. The purpose of creating a test step block is for better readability and understanding of Test Cases.

For example, application login functionality is involved with steps – invoke browser, enter credential, and login verification. In this particular example, we need to create a folder within the test case which will be represented as test step block. Then, we will rename it to ApplicationLogin  and create three steps.

Test Step Library – It’s a location to create our reusable test step components. The Library can be created under any folder available in the Test Cases section. There is a limitation that we can not create more than one Library within a root folder.

Library creation – First, need to right-click on any folder available in TestCase section and select the “create teststep library” folder icon with L symbol. The shortcut keys to create library folder are the combination of  “Ctrl+N” and “Ctrl+L”.

Tosca Automation Tool - Tosca Library
Tosca Automation Tool – Tosca Library

Tosca Execution:

Once we have created test cases in the TestCases section of Tosca Commander, we can proceed with one of the following options for test execution –

· Execution in Tosca ScratchBook

· Execution in Tosca ExecutionList

Execution in ScratchBook: It is advisable to execute test cases in ScratchBook to ensure the test case completeness during the test development and maintenance phase. The execution log created in scratchbook will not available for future reference as it’s a kind of temporary log. We can also drill down and execute individual TestSteps as well.

Execution in ExecutionList: The actual test execution cycle has to be done from ExecutionList which are created for the particular cycle. The result logs which are created in ExecutionList can be used for future reference. This logs are saved in common repository. We can integrate the execution list with external system for continuous testing.

Get more details on Tosca execution, please click here.

Conclusion:

Through this article, we have learned about the overview of different Tosca Automation activities such as, Tosca Automation Tool, Tosca Workspace, Tosca Commander and Tosca Automation. Also, please click here to understand more from Tricentie Support portal.

Puppeteer Automation Testing: Tutorial 6

Puppeteer Automation Testing Open Chrome Developer tool 300x169 1

The Puppeteer is a node js library based framework which is available as open-source. It can be used for web scraping tools. It’s also used for test automation tools as well. Now-a-days, the usage of Puppeteer is getting increased rapidly in the automated software testing space. Basic knowledge of command line, Javascript, and HTML DOM structure is required to understand puppeteer tutorial. The entire tutorial is segregated into the below articles. 

Puppeteer Tutorial

Tosca Tutorial #1: Puppeteer Overview

Tosca Tutorial #2: Puppeteer Environment Variables

Tosca Tutorial #3: Puppeteer Web Scraping and Puppeteer Test Automation Overview

Tosca Tutorial #4: Install Puppeteer

Tosca Tutorial #5: Sample Puppeteer Project

Tosca Tutorial #6: Puppeteer Automation Testing

In this “Puppeteer Automation Testing” tutorial, we will explain the detailed steps for Puppeteer Automation from the beginning. Below features will be explained to understand Puppeteer Automation testing from scratch –

· Install Puppeteer

· Launch Web Application

· Identify object properties from the Chrome Browser

· Form Submission steps – Enter text, Click event, Verification

· Screenshot capture

· Execute scripts for Puppeteer Automation

Puppeteer Automation

Testing is required to ensure the quality of software products. There are multiple levels of testing defined in the software development processes. To test the functionalities of a software, can be done manually or through automated process. The main purposes of automated software testing are –

  • Fast test execution cycle.
  • Avoid the chances of human errors.
  • Reduce the test execution timing.
  • Reduce the release cycle time.
  • Cove more functionality with out compromising with quality.
  • Multiple execution can be done parallelly.

 Puppeteer is a javascript based Node library that gives a high-level application interface(API) to control the Chrome web browser over the Chrome DevTools protocol. Most of the manual operations performed in the Chrome browser can be automated using Puppeteer. So, the Puppeteer is a good choice for unit testing on web applications fast and easier way. 

Puppeteer Automation Testing Approach:

The steps involved with Puppeteer Automation Testing are explained below – 

Step1# Identify Functional Test Scenario:

We will show the step by step approach to performing Puppeteer automation for the below scenario – 

· Launch the Web Browser.

· Invoke Amazon Web application.

  • Search for the book “Testing Book”.
  • Add the book into the cart from the result.
  • Open cart and check if the book is available in the cart.
  • Capture screen and close the browser.

Step2# Install Puppeteer and Create Test Case:

Create an empty javascript file as “sample_script.js” in a specific folder. Here, we will consider the root folder as SampleProject. To install Puppeteer, we will use the command – “npm install puppeteer”. The installation procedure takes some time based on the network speed. It will download approximately 350MBs of data. After installation, the node_modules folder, which contains different puppeteer components and package-lock.json file, will be created to the sample Puppeteer project root folder.

Step3# Capture Identification Properties of the Test Object:

We can capture the identification properties using the Developers Tool of Chrome web browser. Analyzing the different properties such as, id, name, XPath, etc., we will pick the correct one which can be used in the scripting to perform any operations. In this “Puppeteer Automation Testing” tutorial, we will use the XPath in the script. Below steps to follow to get the XPATH or any other properties,

1. Open Developer Tools which available under “Menu -> More tools”, and go to Elements tab.

2. Using the Finder tool (clicking on arrow icon available in the left top corner of the Elements tab), highlight the test object from the application. Here, we will inspect the search box.

Puppeteer Automation Testing - Open Chrome Developer tool
Puppeteer Automation Testing – Open Chrome Developer tool

3. Analyze the highlighted source code to identify desire properties. To get the XPATH property of the test object, right-click on the highlighted section and click on “Copy-> Copy Xpath” to copy the XPATH property in the clipboard.

Puppeteer Automation Testing - Copy XPath
Puppeteer Automation Testing – Copy XPath

4. Now, paste the Xpath in the finder textbox and press enter to check if the Xpath is identifying the object uniquely.

Puppeteer Automation Testing - Check XPath
Puppeteer Automation Testing – Check XPath

5. Similarly, we need to capture the identification properties for another test object as well.

Step4# Puppeteer Automation Development Steps:

In order to complete the test case, we need to perform certain operations on web pages. For each of the operation, there are different methods available. The methods which are used in our scenario for “Puppeteer Automation Testing” are explained here.

Launch Application – After including the puppeteer, we need to launch the browser using the puppeteer—launch method. An object reference can be passed to this method to define for headless or headful browser. Then we need to create the instance of the web browser which is required to navigate the URL. Here, the async function is used to use the await keyword to handle the web synchronizer.

//Include the puppeteer package
const puppeteer = require('puppeteer'); 
 (async () => {
    //launching the headless browser
    const browser = await puppeteer.launch({ headless: true });
   //Create instance of the browser
    const page = await browser.newPage();
   //Navigate to the url
    await page.goto('https://www.amazon.in/');
  })()

The entire testing will be done in a headless browser. If we want to open the headful browser, we need to pass the object to the launch method as “{headless: false}”.

Check the existence – We need to use the method page.waitForXpath which will check the existence of the Xpath and return the reference of the test object. By testing the return reference, we can add a verification point in the test case.

\tlet searchBox = await page.waitForXPath("//*[@id='twotabsearchtextbox']",{ visible: true });
\tif (searchBox === null) //Verification of the test object
\t{
\t\tconsole.log('Amazon screen is not displayed');
\t}

Enter Data – Using the type method of that object reference, we can enter the text.

await searchBox.type("Testing Book");

Click on Element  – Similarly, using the click method of any object reference, we can perform click operations.

let btnSearch = await page.waitForXPath("//*/input[@id='nav-search-submit-button']",{visible:true });
btnSearch.click();

Print message in the console  – Using the method console.log, we can print any message in the console as output.

console.log(‘Console lag has been generated’);

Refer to the new tab – Using the methods page.target and browser.waitforTarget, we can check and store the reference about new tab into a variable.

\tconst pageTarget = page.target();
\tconst newTarget = await browser.waitForTarget(target => target.opener() === pageTarget);
\t//get the new page object:
\tconst page2 = await newTarget.page();

Capture Screenshot – Using the method page. Screenshot, a snapshot of the particular page has been taken and save as per the file name provided as an argument.

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

Close Page and Browser – Using the method close, we can close both the web page and the browser.

\tawait page.close();
\tawait browser.close();

Wait Time – In certain cases, there is a requirement to wait for page loading or finishing of any dependant task; we need to pause the execution for a pre-defined time. To perform this, we can use the page.waitForTimeout method which can pause the execution based on the value (in mili-seconds) passed through the argument.

await page.waitForTimeout(2000);

Now we have learned about the basic technical steps to automate our functional scenario. Based on the knowledge, we can go through the Puppeteer Automation test case below. The detailed overview of the most frequently used classes and methods will be explained in subsequent posts.

/**
 * @name Amazon search
 */
const puppeteer = require('puppeteer');
const reportPath = 'C:\\\\LambdaGeeks\\\\puppteer_proj_sample\\\\output\\\\';
const screenshot = 'screen1.png';
// Used to export the file into a .docx file
try {
  (async () => {
    const browser = await puppeteer.launch({ headless: false });
    const pageNew = await browser.newPage()
    await pageNew.setViewport({ width: 1280, height: 800 });
    await pageNew.goto('https://www.amazon.in/');
\t//Enter Search criteria
\tlet searchBox = await page.waitForXPath("//*[@id='twotabsearchtextbox']",{ visible: true });
\tif (searchBox === null)
\t{
\t\tconsole.log('Amazon screen is not displayed');
\t}
\telse{\t\t
\t\tawait searchBox.type("Testing Book");
\t\tconsole.log('Search criteria has been entered');
\t} \t\t
\t//Clicked on search button
\tlet btnSearch = await pageNew.waitForXPath("//*/input[@id='nav-search-submit-button']",{ visible: true });
\tif (btnSearch === null)
\t{
\t\tconsole.log('Search button is not showing');
\t}
\telse{
\t\tawait btnSearch.click();
\t\tconsole.log('Clicked on search button');
\t}\t
\t//Click on specific search result
\tlet myBook = await pageNew.waitForXPath("//*[contains(text(),'Selenium Testing Tools Cookbook Second Edition')]",{ visible: true })
\tif (myBook === null)
\t{
\t\tconsole.log('Book is not available');
\t}
\telse{
\t\tawait myBook.click();
\t\tconsole.log('Click on specific book to order');
\t} \t
\t// Identify if the new tab has opened
\tconst pageTarget = pageNew.target();
\tconst newTarget = await browser.waitForTarget(target => target.opener() === pageTarget);
\t//get the new page object:
\tconst page2 = await newTarget.pageNew();\t
\tawait page2.setViewport({ width: 1280, height: 800 });
\t
\t//Add to cart
\tlet addToCart = await page2.waitForXPath("//*/input[@id='add-to-cart-button']",{ visible: true });
\tif (addToCart === null)
\t{
\t\tconsole.log('Add to cart button is not available');
\t}
\telse{
\t\tconsole.log('Click on add to Cart button');
\t\tawait addToCart.click();\t\t
\t} \t\t
\t//Verify add to cart process\t
\tlet successMessage = await page2.waitForXPath("//*[contains(text(),'Added to Cart')]",{ visible: true });
\tif (successMessage === null)
\t{
\t\tconsole.log('Item is not added to cart');
\t}
\telse{
\t\tconsole.log('Item is added to cart successfully');\t\t
\t} \t\t
\t// Capture no of cart
\tlet cartCount = await page2.waitForXPath("//*/span[@id='nav-cart-count']",{ visible: true});
\tlet value = await page2.evaluate(el => el.textContent, cartCount)
\tconsole.log('Cart count: ' + value);
\tcartCount.focus();
\tawait page2.screenshot({ path: screenshot });
\t
\tawait pageNew.waitForTimeout(2000);    
\tawait page2.close();
\tawait pageNew.close();
    await browser.close();
  })()
} catch (err) {
  console.error(err)
}

Step5# Puppeteer Automation Test Execution:

We can initiate the execution using the command node sample_script.js through the command prompt. During the execution, Chromium browser will be opened and automatically performed the functional steps and store the screenshot of the final page. The screenshot and the console output will look like below.

Puppeteer Automation Testing - Console Output
Puppeteer Automation Testing – Console Output
Puppeteer Automation Testing - Captured Screen
Puppeteer Automation Testing – Captured Screen

Conclusion:

Throughout this Puppeteer Automation Testing Tutorial, we have learned about the detailed steps on Puppeteer Automation Testing. In the next Puppeteer tutorial, we will learn about the detailed overview of the most frequently used puppeteer classes and methods. Please click here to visit the reference portal for this Puppeteer Tutorial. 

Install Puppeteer – An Excellent Learning Guide of Puppeteer Tutorial 4 & 5

Puppeteer tutorial Install NodeJs

Puppeteer is an open-source node js library that can be used for web scraping tools. It can also be used to perform test automation in web applications. Now-a-days, the usage of Puppeteer is getting increased rapidly in the automated software testing space. Basic knowledge of command line, Javascript, and HTML DOM structure is required to understand puppeteer tutorial. The entire tutorial is segregated into the below articles. 

Puppeteer Tutorial

Tosca Tutorial #1: Puppeteer Overview

Tosca Tutorial #2: Puppeteer Environment Variables

Tosca Tutorial #3: Puppeteer Web Scraping and Puppeteer Test Automation Overview

Tosca Tutorial #4: Install Puppeteer

Tosca Tutorial #5: Sample Puppeteer Project

In this Puppeteer Tutorial, we will learn about the steps to install Puppeteer with its dependencies such as install NodeJs, install editor for Puppeteer, etc. Also, after installation, we will create and execute one sample Puppeteer project.

Install Puppeteer

To start the development of Puppeteer scripts, we need to install and configure the below components – 

1. Install NodeJS

2. Install Editor

3. Install Puppeteer

Install NodeJS:

NodeJs is a free open source server environment which can be run in different platforms. It uses javascript in the server side. The Puppeteer is one kind of NodeJS application. So the first step of Puppeteer setup is to install the NodeJS framework. The NodeJS framework is available for multiple platforms, including Windows, Ubuntu, macOS, etc. In this context, we will work on the version for 64 bit Windows operating system. The steps to install NodeJS are –

Step1# Download NodeJS: Click here to navigate the NodeJS download link. Here, we will download the 64 bit windows installer (.mts). 

Puppeteer tutorial - Install NodeJs
Puppeteer tutorial – Install NodeJs

Step2# Install NodeJS: After completion of the download, we need to install NodeJs by double-clicking on the installer(.msi) file. During the installation, we need to proceed according to instructions.

Step3# Verify NodeJS: After the completion of the installation, we need to open the command prompt and enter the command as “node”. If the below details are appearing, the installation is correct. In case, if there is any error appears, that means installation is not correct.

Puppeteer tutorial - Verify NodeJs
Puppeteer tutorial – Verify NodeJs

Install Editor for Puppeteer:

An editor is nothing but a tool that helps us to write, compile and run our Puppeteer codes. There many tools are available which can be used as a java code editor which includes Visual Studio Code, Note Pad ++, Edit Plus, etc. Even we can write puppeteer code in the default “Note Pad” application as well. In this “Install Puppeteer” tutorial, we will use VSCode as it’s free and easily compatible with NodeJS Application. VSCode is nothing but one component of visual studio, which is available for free. Steps to install VSCode are – 

Step1# Downloadd VSCode: Click here to open the download link and download the desire version of VSCode Installer as per the operating system.

Step2# Install VSCode: Install VSCode from the installer file in the system just like any other software. During the installation, proceed with recommended setting only.

Step2# Verify VSCode: After the completion of the installation, open the application to check whether it’s installed correctly.

Puppeteer tutorial - Editor for Puppeteer
Puppeteer tutorial – Editor for Puppeteer

Install Puppeteer Packages:

From the version v1.7.0 of puppeteer, every release contains below two packages –

  • puppeteer-core package
  • puppeteer package

Both the versions of Puppeteer can be installed using the console commands. The commands to install Puppeteer are – 

Install Puppeteer-core Package: It’s a collection of Node JS library which is developed in Java. It has the ability to work on devtools protocol. The Chromium browser is not getting downloaded while installing the puppeteer-core package. The programmatic interface of Puppeteer completely drives the puppeteer-core library. Another important limitation is that the puppeteer-core features can’t be altered by changing any of the PUPPETEER_* environment variables. 

Installation Command: npm install puppeteer-core

Note: The Node JS tool need to be installed before installing the puppeteer-core package.

Install Puppeteer Product Package: Puppeteer is the complete product which is developed by Google to controls the Chrome browsers. Being the complete Puppeteer product package, the latest versions of chromium browser is getting downloaded during the installation. After that the installation is driven by puppeteer-core. It’s possible to customize the Puppeteer features by changing the PUPPETEER_* environment variables. 

Installation Command: npm install puppeteer

In this “Install Puppeteer” tutorial, we will work on the Puppeteer package installation as there are not many differences between these two versions.

Sample Puppeteer Project

The Puppeteer is compatible with both headful (non-headless) and headless chrome browsers. In case of headless, the browser activities are performed in the background i.e. the browser UI is not visible to us.  It make the thing (controlling the browser) simpler and easier in single step. It means, same thing(controlling the browsers) can be done with multiple complex steps.

The steps involved in setup sample Puppeteer project are shown below – 

Step1# Create a folder structure for Sample Puppeteer Project: Create a sample root directory with the name “SampleProject” in a pre-defined path. This root directory will be acted as a Sample Puppeteer Project. Next, after opening the command prompt, we need to navigate to this root directory.

Step2# Install Puppeteer: Using the below command, we can install the full package of Puppeteer in the root directory. This command basically downloads all the open-source NodeJS libraries in the sample project folder. The installation procedure takes some time based on the network speed. It will download approximately 350MBs of data. After installation, the node_modules folder, which contains different puppeteer components and package-lock.json file, will be created to the sample Pupeteer project root folder.

Puppeteer tutorial - Installation Log
Puppeteer tutorial – Installation Log

Step3# Create Sample Puppeteer Script: Now, we will write a sample puppeteer script that invokes the LambdaGeeks website, displays console messages after each step, and capture the screenshot. In this example, a headless chromium-browser will be invoked in the background. The sample Puppeteer Script will be – 

const puppeteer = require('puppeteer'); //include Puppeteer Library
 
puppeteer.launch({headless:true}).then(async browser => {
     const pageNew = await browser.newPage(); // Launch browser
     console.log('Step1 - Open Browser'); //Display message
     await pageNew .setViewport({ width: 1280, height: 800 })
     await pageNew .goto('https://techiescience.com/'); //Open LambdaGeeks
     //Capture Screenshot
     await pageNew .screenshot({ path: 'screenshot_lambda.png' });
     console.log('Step2 - Navigate LambdaGeeks and take screenshot');
     await browser.close();
     console.log('Step3 - Browser Closed');
 });

This code needs to be stored in the root directory of the Sample puppeteer project with the file name sample_script.js. Incase of Puppeteer-core, we need to include ‘puppeteer-core’ instead of ‘puppeteer’ at the very beginning of the script. For headful browser, we need to replace code “{headless:true}” with “{headless:false}”.

Step4# Execute Sample Puppeteer Script: The sample script can be executed from the command prompt using the below command –

npm node sample_script.js

After the execution, the screenshot will be capture and store in the root directory as “’screenshot_lambda.png”.

Puppeteer tutorial - Sample Puppeteer Project
Puppeteer tutorial – Sample Puppeteer Project

Now we will shown another sample Puppeteer script on amazon web application. This script will perform below steps along with verifications in each steps –

  • Invoke Amazon application.
  • Search a predefined book.
  • Add the searched book into cart.
  • Open cart and check if the book is available in cart.
  • Capture screen and close the browser.

We will only walk through the below script. We will learn in details about different steps to perform in next article. The sample script is shown below –

/**
 * @name Search in Amazon
*/
const puppeteer = require('puppeteer');
const reportPathDir = 'C:\\\\LambdaGeeks\\\\puppteer_proj_sample\\\\output\\\\';
const screenshotFile = 'screen1.png';
try {
  (async () => {
    
\t//Create browser and page object instance and navigate to the URL
    const browserWeb = await puppeteer.launch({ headless: false });
    const pageWeb = await browserWeb.newPage()
    await pageWeb.setViewport({ width: 1280, height: 800 });
    await pageWeb.goto('https://www.amazon.in/');
\t
\t//Enter the amazon Search criteria
\tlet searchBoxAmazon = await pageWeb.waitForXPath("//*/input[@id='twotabsearchtextbox']",{ visible: true });
\tif (searchBoxAmazon === null)
\t{
\t\tconsole.log('Amazon screen is not displayed');
\t}
\telse{\t\t
\t\tawait searchBoxAmazon.type("Testing Book");
\t\tconsole.log('Search criteria has been entered');
\t} \t\t
\t
\t//Clicked on search button
\tlet btnSearchAmazon = await pageWeb.waitForXPath("//*/input[@id='nav-search-submit-button']",{ visible: true });
\tif (btnSearchAmazon === null)
\t{
\t\tconsole.log('Search button is not showing');
\t}
\telse{
\t\tawait btnSearchAmazon.click();
\t\tconsole.log('Clicked on search button');
\t}\t
\t
\t//Click on specific search result
\tlet myBookAmazon = await pageWeb.waitForXPath("//*[contains(text(),'Selenium Testing Tools Cookbook Second Edition')]",{ visible: true })
\tif (myBookAmazon === null)
\t{
\t\tconsole.log('Book is not available');
\t}
\telse{
\t\tawait myBookAmazon.click();
\t\tconsole.log('Click on specific book to order');
\t} \t
\t
\t// Identify if the new tab has opened
\tconst pageTarget = pageWeb.target();
\tconst newTarget = await browserWeb.waitForTarget(target => target.opener() === pageTarget);
\t//get the new page object:
\tconst page2 = await newTarget.page();\t
\tawait page2.setViewport({ width: 1280, height: 800 });
\t
\t//Add to cart
\tlet addToCartAmazon = await page2.waitForXPath("//*/input[@id='add-to-cart-button']",{ visible: true });
\tif (addToCartAmazon === null)
\t{
\t\tconsole.log('Add to cart button is not available');
\t}
\telse{
\t\tconsole.log('Click on add to Cart button');
\t\tawait addToCartAmazon.click();\t\t
\t} \t\t
\t//Verify add to cart process\t
\tlet successMessageAmazon = await page2.waitForXPath("//*[contains(text(),'Added to Cart')]",{ visible: true });
\tif (successMessageAmazon === null)
\t{
\t\tconsole.log('Item is not added to cart');
\t}
\telse{
\t\tconsole.log('Item is added to cart successfully');\t\t
\t} \t
\t
\t// Capture no of cart
\tlet cartCountAmazon = await page2.waitForXPath("//*/span[@id='nav-cart-count']",{ visible: true});
\tlet valueCount = await page2.evaluate(el => el.textContent, cartCountAmazon)
\tconsole.log('Cart count: ' + valueCount);
\tcartCountAmazon.focus();
\tawait page2.screenshot({ path: screenshotFile });
\t
\tawait pageWeb.waitForTimeout(3000);    
\tawait page2.close();
\tawait pageWeb.close();
    await browserWeb.close();
  })()
} catch (e) {
  console.log(e)
}

Note: We will explain the details steps to write scripts in next articles.

Conclusion:

In this introductory article about “Install Puppeteer” from the “Puppeteer Tutorial”, we have explained about the detailed steps to install different Puppeteer packages from the scratch. The puppeteer setup includes different component installations such as, install NodeJs, install VSCode, install Puppeteer, create and execute Puppeteer sample project. In the next Puppeteer tutorial, we will explain detailed steps to use the Puppeteer as a web scraping tool. Please click  here to read from reference portal.

Puppeteer Web Scraping and Test Automation – An Excellent Learning Guide of Puppeteer Tutorial 3

Puppeteer Tutorial Puppeteer Web Scraping 300x139 1

Now-a-days, the Puppeteer is getting more attention as a web scraping tool. Due to the simplicity , the availability as a open-source tool and ability to develop single page application, Puppeteer is getting the popularity. Prior to start learning on Puppeteer web scraping tool, we should have basic understanding of command line, Javascript, and HTML DOM structure. The Puppeteer tutorial has been broken into few articles which are specified in below table of content.

Puppeteer Tutorial

Tosca Tutorial #1: Puppeteer Overview

Tosca Tutorial #2: Puppeteer Environment Variables

Tosca Tutorial #3: Puppeteer Web Scraping and Puppeteer Test Automation Overview

Tosca Tutorial #4: Install Puppeteer 

In this article of Puppeteer Tutorial, we will discuss Puppeteer Web Scraping with an example and Puppeteer Test automation overview. 

Puppeteer Web Scraping

The process of data extraction from any web pages is called web scraping. Web scraping has two steps. Firstly, it fetches the web page and then extracts the data. After data extraction, we can use it for any API or store it in a CSV file. 

Puppeteer is one of the best tools to support web scraping for Google Chrome or Chromium browser. The puppeteer web scraping is explained in details with the below example – 

Basic Puppeteer Web Scraping Example:

Step1# The Puppeteer works on Node JS library. So, the first step is to include the puppeteer library before writing the script for web scraping.

const puppeteerObj = require("puppeteer");

Step2# After including the Puppeteer class, we need to write an async function by using await keyword. It’s required as Puppeteer uses promises. Then call the Puppeteer.launch() method to invoke the browser and call newPage() method to create web page instance.

const browserWeb = await puppeteerObj.launch();
const pageWeb = await browserWeb.newPage();

Step3# Now call the page.goto() method to provide the URL of the desired website.

await pageWeb.goto("https://techiescience.com/");

Step4# Use the method page.evaluate() to capture the text of any particular element (in this example, we will capture the header text). 

const data = await pageWeb.evaluate(() => {   
const header = document.querySelector(".uabb-heading-text").innerText;
return { header };

We will discuss how to identify any object from the web screen in the upcoming tutorial.

Puppeteer Tutorial - Puppeteer Web Scraping
Puppeteer Tutorial – Puppeteer Web Scraping

Step5# In this last step, we need to process the data and then close the web page. The complete Puppeteer Web Scraping code will be looks like below –

const puppeteer = require("puppeteer");

async function scrap() {
  // Launch the browser
  const browserApp = await puppeteer.launch();
  // Create a page instance
  const pageApp = await browserApp.newPage();
  // invoke the web page for scraping
  await pageApp.goto("https://techiescience.com/");

  // Select any web element
const data = await pageApp.evaluate(() => {   
const header = document.querySelector(".uabb-heading-text").innerText;
return { header };

// Here we can do anything with this data. Here displaying the data
console.log(header);

 //We close the browser
  await browserApp.close();
}

Scrap();

Step6# Now, we can execute this puppeteer web scraping code using the command:  node index.js

Note: In the next article, “Install Puppeteer,” we will discuss the installation setup of Puppeteer and execute the above Puppeteer Web Scraping code.

Puppeteer Test Automation Overview

Apart from web scraping, the Puppeteer has the features to perform the below activities as well,

  • Capture the screenshots of web pages.
  • We can save the screen of web page as a pdf file.
  • Automation of manual steps can be achieved to perform UI testing.

So, combining all the above features, we can use the Puppeteer for test automation. To understand the Puppeteer Test Automation, first, we need to familiar with software testing.

Testing overview:

Testing is required to ensure all the software requirements are fulfilled with out any issues. Different types of testing cycles are available from the beginning of the software development process. Software can be tested manually or through the automated approach.

Purposes of software testing are –

  • Verify the quality of the products.
  • Find the bugs of the product before the production deployment.
  • Checking of requirements are satisfied.
  • Testing the product’s performances.

The types of testing are explained here –

Unit Testing – The developers are the responsible to perform unit testing during the code development phase.

Integration Testing – This testing is required after integrating the different components of the software product. The main purpose is to ensure that all the interfaces are working smoothly.

System Testing – It’s a detailed testing which has to be done after the integration to ensure about all the requirements are fulfilled.

User Acceptance Testing – It’s also a detailed testing which has to be done by the end user of the product to ensure the quality.

Regressing Testing – It’s required to ensure the core business process are working smoothly during any software enhancements.

Advantages of Test Automation:

  • Reduce the execution cycle.
  • Avoid the chances of human errors.
  • Minimize the test execution efforts.
  • Fast software release.
  • Increase the testing coverage to reduce the risk.
  • Ability to perform parallel execution.

Why Puppeteer?

Most of the manual operations performed in the Chrome browser can be automated using Puppeteer. So, the Puppeteer is a good choice for unit testing on web applications fast and easier way. 

The limitations of Puppeteer as an automation testing tool are –

  • Only supports Chrome and Chromium browser.
  • Coss-browser testing is not possible.
  • Mobile testing can not be done.

Headless Chrome Testing:

The headless browser means the Puppeteer is interacting with a chrome browser as a background application, which means that the chrome UI is not visible on the screen. So, the headless chrome testing means the automation testing is to be performed in a hidden browser. Also, after the headless chrome testing, the Puppeteer is able to capture the web screen properly.

Puppeteer vs Selenium

The comparison between Puppeteer and Selenium as an automation testing tool are explained below –

  • Programming language support – Puppeteer supports only JavaScript, where Selenium support Java, Python, Node.js, and C# languages.
  • Browser Support – Puppeteer is applicable only for Chrome or Chromium browser, but Selenium supports Chrome, Mozilla, Safari, IE, Opera browsers as well.
  • Community Support – Community support restricted to Google Groups, GitHub, and Stack Overflow for the Puppeteer. But for Selenium, wide community support over multiple forums is available.
  • Execution Speed – Execution of Puppeteer script is faster than Selenium.
  • Installation and Setup – Puppeteer installation and setup is a more easy and simple process.
  • Cross-Platform Support – Puppeteer does not support it, but Selenium can.
  • Recording – Recording features are not available in Puppeteer. But this feature is available for Selenium IDE.
  • Screenshots – Puppeteer has the capability to take a screenshot as an image or pdf format, where Selenium can support only image format.
  • Testing Platform Support – Puppeteer only supports web browsers, but Selenium can automate web and mobile with Appium.
  • Coding Skills – It is required for Puppeteer Selenium Web driver but not for Selenium IDE.

Based on the above comparison, we can conclude that Puppeteer will make the best choice when we have to perform unit level testing for any web application where a fast and flexible solution is required. The other tool, Selenium will be the better choice when there is a need for mobile application and cross-platform application testing. Click here to learn Selenium from LambdaGeeks.

Conclusion:

In this introductory article on Puppeteer Tutorial, we have learned about Puppeteer Web Scraping and Puppeteer Test Automation overview. We will learn about the step by step guide to install Puppeteer and execute a small script in the next Puppeteer article. Please click here to visit the reference portal for this Puppeteer Tutorial.

Puppeteer Tutorial– An Excellent Learning Guide of Puppeteer Tutorial 1 & 2

Puppeteer Tutorial Puppeteer 209x300 1

The Puppeteer is an open-sourced java framework which is developed with node-js library. The Puppeteer has the ability to work as a web scraping tool. It can be also used as a test automation for web based applications just like selenium web driver. The popularity of Puppeteer is getting increased rapidly for test automation. The pre-requisites to walk through the Puppeteer Tutorial, are basic knowledge of command line, JavaScript, OOPs concept and HTML DOM structure. The complete Puppeteer tutorial is distributed into topics which are mentioned in the below table of content. 

Puppeteer Tutorial

Tosca Tutorial #1: Puppeteer Overview

Tosca Tutorial #2: Puppeteer Environment Variables

Tosca Tutorial #3: Puppeteer Web Scraping and Puppeteer Test Automation Overview

Tosca Tutorial #4: Install Puppeteer 

In this article of Puppeteer Tutorial, we will explain about Puppeteer Overview and Puppeteer Environment Variables. 

Puppeteer Overview

The Puppeteer is an open-sourced java framework which is developed with node-js library. Puppeteer is able to control Chrome browser over the devtool protocol with the help of the high-level application interface(API). The Puppeteer is able to control both headful and headless chrome browsers. 

The Puppeteer framework is introduced by Google. As per the functionality, it’s not a new concept. But it make the work easier. Fundamentally, it summaries a list of activities through a compacted package.

Puppeteer Tutorial - Puppeteer
Puppeteer Tutorial – Puppeteer

How do Puppeteers work?

  • Puppeteer uses the Node JS library.
  • The Node JS allows to use the high-level APIs.
  • The APIs are capable of controlling the Chrome browser over devtool protocol.
  • By default, Puppeteer works with headless Chrome browsers but it can interact with headful Chrome browsers as well by changing the default configuration.

Chrome DevTools Protocol:

Using the Chrome DevTools Protocol, tools like Puppeteer are able to instrument, inspect, debug and profile the blink-based browsers such as Chromium, Chrome, etc.

Here, the instrumentation of the browser is divided into a number of domains such as DOM, Debugger, Network, etc. The every domain explains all the different supported commands and the generated events.

Features of Puppeteer:

  • The manual processes through the Chrome browser can be automated.
  • It can captures screenshot of any web page and generates the image or pdf file of the screenshot.
  • A single page application can be developed of server side rendering using the Puppeteer.
  • It can automate the web form submission, UI testing, keyboard input, etc., with checkpoints.
  • It provides more control over the Chrome browser.
  • The default headless mode is very fast.
  • It supports web scraping.
  • Ability to measures rendering and load timing using Chrome performance analysis tools.

Puppeteer vs Puppeteer-core:

Since Puppeteer version v1.7.0, below two packages, are available in every release –

  • puppeteer-core package
  • puppeteer package

Puppeteer-core Package:

Puppeteer-core is a java-base Node library that is able to perform any operation that supports the DevTools protocol. The Puppeteer-core doesn’t download Chromium during the installation. As a library, Puppeteer-core is completely driven through its programmatic interface. Also, the features of Puppeteer-core can’t be customized by all PUPPETEER_* env variables. The basic command to install Puppeteer-core – 

npm install puppeteer-core
# or "yarn add puppeteer-core"

When using puppeteer-core, include statements will be looks like below –

const puppeteer = require('puppeteer-core')

When to use Puppeteer-Core:

  • To develop Puppeteer project to use existing Chrome browser over the DevTools protocol where additional chromium download is not required.
  • To develop another end-user product or library on top of DevTools protocol. For example, one project may build a screenshot generator using puppeteer-core and write a custom setup.js script that downloads headless_shell instead of Chromium to save storage.

Puppeteer Package:

Puppeteer is a complete product for Chrome or Chromium browser automation. During the installation, it downloads the latest version of Chromium, and after that, it was driven by puppeteer-core. As an end-user product, Puppeteer supports all the PUPPETEER_* env variables to customize its behavior. The basic command to install Puppeteer – 

npm install puppeteer
# or "yarn add puppeteer"

When using Puppeteer, include statements that will be looks like below –

puppeteer = require(‘puppeteer’)

Difference between Puppeteer and Puppeteer-core:

  • Puppeteer-core doesn’t download the Chromium browser automatically during installation.
  • Puppeteer-core does not consider all PUPPETEER_* env variables.
  • In most projects, we are using the Puppeteer product package.

Headless Chrome:

Headless chrome means the Puppeteer is interacting with a chrome browser as a background application, which means that the chrome UI is not visible on the screen. By default, Puppeteer launches the application as headless chrome. Code sample to launch Headless Chrome – 

In this example, we are opening the headless chrome, i.e., the Chrome UI will not be visible. It can be done by passing the headless flag as true to the Puppeteer.launch method().

const puppeteer = require('puppeteer');

(async () => {
  const browser = await puppeteer.launch({ headless: true });
  // Specify statements for Headless Chrome operations  
  await browser.close();
})();

Headful Chrome:

Headful chrome means the Puppeteer is interacting with a chrome browser for which chrome UI is visible on the screen. By default, Puppeteer launches the application as headless chrome. Code sample to launch Headful Chrome – 

In this example, we are opening the chrome, which is visible to us. It can be done by passing the headless flag as false to the Puppeteer.launch() method.

const puppeteer = require('puppeteer');

(async () => {
  const browser = await puppeteer.launch({ headless: false});
  // Specify statements for Headless Chrome operations  
  await browser.close();
})();

Puppeteer Environment Variables

Puppeteer works with predefined environment variables to support its operations. If Puppeteer doesn’t find the environment variables during the installation, a lowercased variant of these variables will be used from the npm config (manages the NPM Configurations file). The environment variables are not considered by the Puppeteer-core package. The most important Puppeteer environment variables are – 

  • PUPPETEER_SKIP_CHROMIUM_DOWNLOAD: It instructs not to download bundled Chromium during the installation step.
  • PUPPETEER_DOWNLOAD_HOST: It overwrites URL prefix that can be used to download Chromium. 
  • PUPPETEER_DOWNLOAD_PATH: It overwrites the download folder path. Defaults path is – “<root>/.local-chromium/” where <root> is the package root of puppeteer.
  • HTTP_PROXY, HTTPS_PROXY, NO_PROXY: These variables define the proxy settings to download Chromium during the installation.
  • PUPPETEER_CHROMIUM_REVISION: It defines a specific version of Chromium to be used by the Puppeteer.
  • PUPPETEER_EXECUTABLE_PATH: It specifies an executable path to be used in Puppeteer.launch method. 
  • PUPPETEER_PRODUCT: It defines which browser is to be used by Puppeteer. The value has to be either chrome or firefox. 

Conclusion:

In this introductory article on Puppeteer Tutorial, we have learned about Puppeteer overview and Puppeteer Environment Variables. In the next article of the Puppeteer tutorial, we will learn about the Puppeteer Web Scraping and Puppeteer Test Automation overview. Please click here to visit the reference portal for this Puppeteer Tutorial. Also, please click here to learn Selenium from LambdaGeeks.

VBScript Array Functions – An Excellent Guide for VBScript Tutorial 8

vbscript array functions vbscript array 300x52 1

VBScript Tutorial – Table of Content

VBScript Tutorial #1: Overview of VBScript Variables 

VBScript Tutorial #2: VBScript Conditional Statements and Loops

VBScript Tutorial #3: VBScript Procedures

VBScript Tutorial #4: VBScript Error Handling and Execute VBScript

VBScript Tutorial #5: VBScript String Functions

VBScript Tutorial #6: VBScript Date Functions

VBScript Tutorial #7: VBScript Time Functions

VBScript Tutorial #8: VBScript Array Functions

VBScript Tutorial #9: VBScript Math Functions

VBScript Tutorial #10: VBScript Conversion Functions and VBScript Format Functions

VBScript Tutorial #11: VBScript Other Functions 

Through out this “VBScript Array Functions” article, we will explains the different types of frequently used vbscript array functions with examples. The important functions related to array are vbscript join, vbscript array, vbscript filter, vbscript split, etc.

VBScript Tutorial #8: VBScript Array Functions

VBScript Array Functions:

While working with arrays in vbscript, we can use in-build vbscript array functions to perform important array-related operations such as create, manipulate, conversion, etc. This article (VBScript Array Functions) contains all the important built-in VBScript array functions, which are mostly used in programs. 

VBScript Array Functions – Summary:

  • vbscript Array – Defines an array based on given data values.
  • vbscript Filter – Defines a array which is a subset of another one-dimensional string array. The new array is created based on filter criteria.
  • vbscript IsArray – Test a array variable and return a Boolean value based on the result.
  • vbscript Join – Converts an array and returns a string value where all the array elements are separated by a specific delimiter.
  • vbscript Split – Converts a string into a zero-based, one-dimensional array.
  • vbscript LBound – Returns the lower index of an array.
  • vbscript UBound – Returns the upper index of an array that indicates the dimension.

VBScript Array Functions – Details:

All the important vbscript array functions are explained in this section with a proper example.

vbscript Array:

vbscript array function defines an array based on given data values. The array elements are passed the arguments in the vbscript array function.

Syntax: Array(arglist)

Parameter Description:

arglist – These are the mandatory parameters. The list(separated by comma) of arguments are basically the elements of the array.

Example:

In the below example, we will create an array of weekdays using vbscript array function and display the first day of the week (0 index) in a message box.

dayArray = Array("Mon","Tue","Wed","Thu","Fri","Sat","Sun")
msgbox "The first day of week: " & dayArray(0)
Output (Message Box): 
The first day of week: Mon
vbscript array functions - vbscript array
vbscript array functions – vbscript array

vbscript Filter:

vbscript filter function defines a zero-based array that contains a subset of a one-dimensional string array. The one-dimensional new array is created based on filter criteria.

Syntax: Filter(string_array,value[,include[,compare]])

Parameter Description:

string_array – It’s a mandatory parameter which indicates a one-dimensional array of string.

value – It’s a mandatory parameter which represents the filter criteria, i.e. the string expression to search in the array.

include – It’s an optional Boolean parameter. If we provide “true” value as include parameter, it includes the elements which contain the searched criteria. Else, it will exclude the elements which contain the criteria. The default value is true.

compare – This is also an optional parameter which specifies the comparison type as binary or textual. If not specified, by default parameter value will be treated as zero. The possible values are – 

· 0 = vbBinaryCompare – Perform a binary checking

· 1 = vbTextCompare – Perform a textual checking

Example:

In the below example, we will create an array using vbscript filter function based on the elements of the weekday array, which contains “S” character.

dayArray = Array("Mon","Tue","Wed","Thu","Fri","Sat","Sun")
filterArray = Filter(dayArray, "S")
for each e in filterArray
\tmsgbox e
next
Output (Message Box): 
Sat
Sun

vbscript IsArray:

vbscript isarray function tests and returns a boolean value after checking a specified variable is an array or not. For a valid array, the return value is true else false will be returned.

Syntax: IsArray(variable)

Parameter Description:

variable – It’s a required parameter which needs to be verified.

Example:

In the below example, we will check a variable if it’s an array or not.

dayArray = Array("Mon","Tue","Wed","Thu","Fri","Sat","Sun")
boolFlag = IsArray(dayArray)
msgbox "Return value: " & boolFlag
Output (Message Box): 
Return value: True

vbscript Join:

vbscript join function converts an array into a string expression where all the array elements are separated by a specific delimiter.

Syntax: Join(array [, delimiter])

Parameter Description:

array – It’s a required parameter which represents a one-dimensional array.

delimiter – It’s an optional parameter which is used to separate each array element after converting into string expression.

Example:

In the below example, we will convert the weekday array into a string expression using vbscript join function where all the elements will be separated by a comma.

dayArray = Array("Mon","Tue","Wed","Thu","Fri","Sat","Sun")
dayString = Join(dayArray, ",")
msgbox "Converted week day string: " & dayString
Output (Message Box): 
Converted week day string: Mon,Tue,Wed,Thu,Fri,Sat,Sun
vbscript array functions - vbscript join
vbscript array functions – vbscript join

vbscript Split:

vbscript split function converts a string into a one-dimensional array where array elements are created based on specific delimiters.

Syntax: Split(expression[, delimiter[,count[,compare]]])

Parameter Description:

Expression – It’s a required parameter which represents a string expression.

delimiter – It’s an optional parameter which is used to differentiate each array elements within the string expression. The default value is space.

count – It’s an optional parameter which represents the count of substring/array elements to be returned. The default value -1 specifies that entire string will be returned as single element of the array.

compare – This is also an optional parameter which specifies the comparison type as binary or textual. If not specified, by default parameter value will be treated as zero. The possible values are – 

· 0 = vbBinaryCompare – Perform a binary checking

· 1 = vbTextCompare – Perform a textual checking

Example:

In the below example, we will convert a string expression, contains all the day name of a week which are separated by semi-column, using vbscript split function. After the conversion, we will display the first and last day of a week.

string_expression = "Mon;Tue;Wed;Thu;Fri;Sat;Sun"
dayArr = Split(string_expression, ";")
msgbox "First day-> " & dayArr(0) & " and Last day-> " & dayArr(6)
Output (Message Box): 
First day-> Mon and Lat day-> Sun
vbscript array functions - vbscript split
vbscript array functions – vbscript split

vbscript LBound:

vbscript lbound function return the lower index, i.e. smallest subscript of an array for the specified dimension. The lbound value for an array is always 0.

Syntax: Lbound(array[,dimension])

Parameter Description:

array – It’s a required parameter which represents a one-dimensional array.

dimension – It’s an optional parameter which indicates the dimension of the array for which smallest subscript will be returned. The value will be 1 for the first dimension, 2 for the second dimension and so on. The default value is 1. 

Example:

In the below example, we will find and display the lower subscript value using vbscript lbound function.

string_expression = "Mon;Tue;Wed;Thu;Fri;Sat;Sun"
dayArr = Split(string_expression, ";")
msgbox "Lbound Value-> " & Lbound(dayArr)
Output (Message Box): 
Lbound Value-> 0

vbscript UBound:

vbscript ubound function return the upper index, i.e. the largest subscript of an array for the specified dimension. The ubound value for an array represent the highest array index i.e. number of element minus one. This function helps to calculate the length of an array.

Syntax: Ubound(array[,dimension])

Parameter Description:

array – It’s a required parameter which represents a one-dimensional array.

dimension – It’s an optional parameter which indicates the dimension of the array for which smallest subscript will be returned. The value will be 1 for the first dimension, 2 for the second dimension and so on. The default value is 1. 

Example:

In the below example, we will find and display the longest subscript value using vbscript ubound function.

string_expression = "Mon;Tue;Wed;Thu;Fri;Sat;Sun"
dayArr = Split(string_expression, ";")
msgbox "Ubound Value-> " & Ubound(dayArr)
Output (Message Box): 
Ubound Value-> 6
vbscript array functions - vbscript ubound
vbscript array functions – vbscript ubound

Conclusion:

Through this VBScript Array Functions article, we have learned about the frequently used VBScript Array Functions such as, vbscript array, vbscript filter, vbscript join, vbscript split function, etc. In the next vbscript tutorial, we will explain more functions on VBScript functions. Please click to read more on vbscript from here.

VBScript Date Functions and VBScript Time Functions – An Excellent Guide for VBScript Tutorial 6 & 7

vbscript date functions vbscript DateAdd 300x102 1

VBScript Tutorial – Table of Content

VBScript Tutorial #1: Overview of VBScript Variables 

VBScript Tutorial #2: VBScript Conditional Statements and Loops

VBScript Tutorial #3: VBScript Procedures

VBScript Tutorial #4: VBScript Error Handling and Execute VBScript

VBScript Tutorial #5: VBScript String Functions

VBScript Tutorial #6: VBScript Date Functions

VBScript Tutorial #7: VBScript Time Functions

VBScript Tutorial #8: VBScript Array Functions

In this VBScript Tutorial, we are going to learn about the most important and frequently used VBScript Date Functions and VBScript Time Functions, including vbscript Cdate, vbscript DateAdd, vbscript date, vbscript time, vbscript FormatDateTime function, etc. All the vbscript date functions and vbscript time functions are explained with examples.

VBScript Tutorial #6: VBScript Date Functions

While working with dates in vbscript, we can use in-build vbscript date functions to perform important date-related operations such as capture system date, date conversion, extract different parts of a date, calculation, formatting, etc. This article(VBScript Date Functions) contains all the important built-in VBScript date functions, which are mostly used in programs. 

VBScript Date Functions – Summary: 

VBScript Date Functions – Details:

All the important vbscript date functions are explained in this section with a proper example.

vbscript Cdate:

vbscript cdate function used to convert a string expression of a date into date format and returns the converted date value. While updating any date type field such as database field with the date data type, we need to convert the string into date format. Otherwise, an error will be thrown.

Syntax: Cdate(date)

Parameter Description:

date – It denotes any valid date and time expression in string format. 

Example:

In the below example, any valid date expression will be converted into date format using vbscript Cdate function.

strDate = "10-Feb-2021"
dtDate = Cdate(strDate)
‘After the date conversion the variable dtDate will hold the value with date format (#10-Feb-2021#).

vbscript Date:

The vbscript date function returns the present system date.

Syntax: Date

Example:

In the below example, we will store the current system date in a variable and display in the message box.

sysDate = Date
msgbox " Current system date is " & sysDate
' OutPut (Msgbox):
' Current system date is 04-Jan-2020

vbscript DateAdd:

vbscript dateadd function returns the calculated date value after adding with specific interval time.

Syntax: DateAdd(interval,number,date)

Parameter Description:

number – It represents any number we want to add. It can be positive(future date) or negative(past date) value.

date – It represents any valid date.

interval – It’s a mandatory parameter which denotes the interval of time. The different interval options are –

· yyyy – Represents the quarter interval.

· q – Represents the quarter interval.

· m – Represents the month interval.

· y – Represents the the day of a year interval.

· d – Represents the day interval.

· w – Represents the weekday interval.

· ww – Represents the week of the year interval.

· h – Represents the hour.

· n – Represents the minute.

· s – Represents the second.

Example:

In the below example, we will calculate the future date after adding two months with the system date using vbscript dateadd function.

sDate = "04-Jan-2021"
newDate = Cdate(sDate)
newDate = DateAdd("m",+2,sDate)
msgbox "Future date after adding 2 months with " & sDate & " is  " & newDate
vbscript date functions - vbscript DateAdd
vbscript date functions – vbscript DateAdd

vbscript DateDiff:

vbscript datediff function returns the number of an interval between two dates.

Syntax: DateDiff(date1,date2[,firstdayofweek[,firstweekofyear]])

Parameter Description:

date1 – It represents any valid date expression.

date2 – It represents any valid date expression.

firstdayofweek – It’s an optional field which denotes the day of the week. The available values are – 

  • 0 = vbUseSystemDayOfWeek (API Setting for National Language Support)
  • 1 = vbSunday (Sunday – default)
  • 2 = vbMonday (Monday)
  • 3 = vbTuesday (Tuesday)
  • 4 = vbWednesday (Wednesday)
  • 5 = vbThursday (Thursday)
  • 6 = vbFriday (Friday)
  • 7 = vbSaturday (Saturday)

firstweekofyear – It’s also an optional field which denotes the first week of the year. The available values are – 

  • 0 = vbUseSystem (API Setting for National Language Support)
  • 1 = vbFirstJan1 (Start with the week when January 1 occurs – default)
  • 2 = vbFirstFourDays (It represent the start week where minimum 4 days are fall in the new year)
  • 3 = vbFirstFullWeek (It represent the week which completely falls in new year)

Example:

In the below example, we are calculating the difference in day interval between two consecutive dates using vbscript datediff function.

date1="04-Jan-2021 00:00:00"
date2="05-Jan-2021 23:59:00" 
diff = DateDiff("d", date1, date2)
msgbox "The date difference - " & diff
' OutPut (Msgbox):
' The date difference - 1
vbscript date functions - vbscript DateDiff
vbscript date functions – vbscript DateDiff

vbscript DatePart:

vbscript datediff function returns the specific part(day, month or year) of any particular date.

Syntax: DatePart(interval,date2,firstdayofweek[,firstweekofyear]])

Parameter Description:

interval – It’s a mandatory parameter which denotes the interval of time. The different interval options are –

· yyyy – Represents the quarter interval.

· q – Represents the quarter interval.

· m – Represents the month interval.

· y – Represents the the day of a year interval.

· d – Represents the day interval.

· w – Represents the weekday interval.

· ww – Represents the week of the year interval.

· h – Represents the hour.

· n – Represents the minute.

· s – Represents the second.

date – It represents any valid date expression.

firstdayofweek – It’s an optional field which denotes the day of the week. The available values are – 

  • 0 = vbUseSystemDayOfWeek (API Setting for National Language Support)
  • 1 = vbSunday (Sunday – default)
  • 2 = vbMonday (Monday)
  • 3 = vbTuesday (Tuesday)
  • 4 = vbWednesday (Wednesday)
  • 5 = vbThursday (Thursday)
  • 6 = vbFriday (Friday)
  • 7 = vbSaturday (Saturday)

firstweekofyear – It’s also an optional field which denotes the first week of the year. The available values are – 

  • 0 = vbUseSystem (API Setting for National Language Support)
  • 1 = vbFirstJan1 (Start with the week when January 1 occurs – default)
  • 2 = vbFirstFourDays (It represent the start week where minimum 4 days are fall in the new year)
  • 3 = vbFirstFullWeek (It represent the week which completely falls in new year)

Example:

Below example evaluates the month part of a given date using vbscript datepart function.

date=Cdate("04-Jan-2021") 
monthPart = DatePart("d", date)
msgbox "The month part - " & monthPart
' OutPut (Msgbox):
' The month part - 1

vbscript IsDate:

vbscript isdate function returns the boolean value as true or false if any string expressing can be converted into date format. Vbscript isdate function is used to test a date expression.

Syntax: Isdate(date)

Parameter Description:

date – It denotes any date expression to be verified. 

Example:

In the below example, any given test expression is checked for the valid date expression.

date = "04-Jan-2021"
boolResult = IsDate(date)
msgbox "Is Valid date ? Ans: " & monthPart
' OutPut (Msgbox):
' Is Valid date ? Ans: true

vbscript Day:

vbscript day function extracts the number(1-31) that represents the day from a valid date expression.

Syntax: Day(date)

Parameter Description:

date – It’s a valid date expression.

Example:

In the below example, the day part will be extracted from a given date using vbscript day function.

date = Cdate("04-Jan-2021")
num = Day(date)
msgbox "The day part is - " & num
' OutPut (Msgbox):
' The day part is - 4

vbscript Month:

vbscript month function extracts  the number(1-12) that represents the month from a valid date expression.

Syntax: Month(date)

Parameter Description:

date – It’s a valid date expression.

Example:

In the below example, month will be extracted from a given date using vbscript month function.

date = Cdate("04-Jan-2021")
num = Month(date)
msgbox "The month part is - " & num
' OutPut (Msgbox):
' The month part is - 1

vbscript Year:

vbscript year function extracts the four digit number that represents the year from a valid date expression.

Syntax: Year(date)

Parameter Description:

date – It’s a valid date expression.

Example:

In the below example, the year will be extracted from a given date using vbscript year function.

date = Cdate("04-Jan-2021")
num = year(date)
msgbox "The year part is - " & num
' OutPut (Msgbox):
' The year part is - 2021

vbscript MonthName:

vbscript monthname function returns the name of a specific month code(1-12).

Syntax: MonthName(month[,abbreviate])

Parameter Description:

month – It’s representing the code(1-12) for any specific month.

abbreviate – It’s not an mandatory parameter. It represents to check about the name of the month is abbreviated or not. The default value is false.

Example:

month_name = MonthName(12)
msgbox "The month name is - " & month_name
' OutPut (Msgbox):
' The month name is - December

vbscript Weekday:

vbscript weekday function returns the number between 1 and 7 that denotes the day of the particular week.

Syntax: WeekDay(date[,firstdayofweek])

Parameter Description:

date – It’s a valid date expression.

firstdayofweek – It’s an optional field which denotes the start day of the week. The available values are –

  • 0 = vbUseSystemDayOfWeek (API Setting for National Language Support)
  • 1 = vbSunday (Sunday – default)
  • 2 = vbMonday (Monday)
  • 3 = vbTuesday (Tuesday)
  • 4 = vbWednesday (Wednesday)
  • 5 = vbThursday (Thursday)
  • 6 = vbFriday (Friday)
  • 7 = vbSaturday (Saturday)

Example:

In the below example, the day representing the week, will be extracted from a given date using vbscript weekday function.

date = Cdate("06-Jan-2021")
num = Weekday(date,1)
msgbox "The week day is - " & num
' OutPut (Msgbox):
' The week day is - 4

vbscript WeekDayName:

vbscript weekdayname function returns the name of a specific day of a week(1-7).

Syntax: WeekDayName(weekday[,abbreviate[,firstdayofweek]])

Parameter Description:

weekday – It’s representing the day code(1-7) for any week.

abbreviateIt’s not an mandatory parameter. It represents to check about the name of the day is abbreviated or not. The default value is false.

firstdayofweek – It’s an optional field which denotes the start day of the week. The available values are –

  • 0 = vbUseSystemDayOfWeek (API Setting for National Language Support)
  • 1 = vbSunday (Sunday – default)
  • 2 = vbMonday (Monday)
  • 3 = vbTuesday (Tuesday)
  • 4 = vbWednesday (Wednesday)
  • 5 = vbThursday (Thursday)
  • 6 = vbFriday (Friday)
  • 7 = vbSaturday (Saturday)

Example:

day_name = WeekdayName(2)
msgbox "The name of the week day - " & day_name
' OutPut (Msgbox):
' The name of the week day - Monday

VBScript Tutorial #7: VBScript Time Functions

While working with time in vbscript, we can use in-build vbscript time functions to perform important time-related operations such as capture system time, extract different parts of any time, calculation, time formatting, etc. This article(VBScript Time Functions) contains all the important built-in VBScript time functions, which are mostly used in programs. 

Important VBScript Time Functions – Summary: 

VBScript Time Functions – Details:

We will explain all the essential vbscript time functions in this section with a proper example.

vbscript Hour:

vbscript hour function extracts the hour of the day as a number between 0 to 23 from time expression.

Syntax: Hour(time)

Parameter Description:

time – It’s a mandatory parameter that represents a valid time expression.

Example:

In the below example, an hour of the day will be extracted from a valid time expression using vbscript hour function.

numHour = Hour("14:40:35")
msgbox "The hour for the day is - " & numHour
' OutPut (Msgbox):
' The hour for the day is - 14

vbscript Minute:

vbscript minute function extracts the minute of the hour as a number between 0 to 59 from time expression.

Syntax: Minute(time)

Parameter Description:

time – It’s a mandatory parameter that represents a valid time expression.

Example:

In the below example, the minute of the hour will be extracted from a valid time expression using vbscript minute function.

numMin = Minute("14:40:35")
msgbox "The minute for the hour is - " & numMin
' OutPut (Msgbox):
' The minute for the hour is - 40

vbscript Second:

vbscript second function extracts the second of the minute as a number between 0 to 59 from time expression.

Syntax: Second(time)

Parameter Description:

time – It’s a mandatory parameter that represents a valid time expression.

Example:

In the below example, the second of the minute will be extracted from a valid time expression using vbscript second function.

numSec = Second("14:40:35")
msgbox "The second for the minute is - " & numSec
' OutPut (Msgbox):
' The second for the minute is - 35

vbscript Time:

vbscript time function returns the current system time.

Syntax: Time

Example:

In the below example, we will store the current system time in a variable and display in a message box.

sysTime = Time
msgbox " Current system time is " & sysTime
' OutPut (Msgbox):
' Current system time is 14:40:35
vbscript time functions - vbscript Time
vbscript time functions – vbscript Time

vbscript Now:

vbscript now function returns the current system date with timestamp.

Syntax: Now

Example:

In the below example, we will store the current system date and time in a variable and display in a message box.

sysTimeStamp = Now
msgbox "Current system date with time is " & sysTimeStamp
' OutPut (Msgbox):
' Current system date with time is 07-Jan-2021 14:40:35

vbscript Timer:

vbscript timer function returns the count of seconds from 12:00 AM.

Syntax: Timer

Example:

secondCounter = Timer
msgbox "Number of seconds since 12:00 AM  " & secondCounter
' OutPut (Msgbox):
' Number of seconds since 12:00 AM 1067.002

vbscript TimeSerial:

vbscript timeserial method fetch the exact time for a mentioned hour, minute  and second.

Syntax: TimeSerial(hour, minute, second)

Parameter Description:

hour – It’s a mandatory numeric parameter, denotes hours.

minute – It’s a mandatory numeric parameter, denotes minutes.

second – It’s a mandatory numeric parameter, denotes seconds.

Example:

In the below example, vbscript timeserial function returns the time for the given hours, minutes and seconds.

time = TimeSerial(15,2,20)
msgbox "Specified time is " & time
' OutPut (Msgbox):
' Specified time is 03:02:20 PM

vbscript FormatDateTime:

vbscript formatdatetime function formats and returns a valid and time expression.

Syntax: FormatDateTime(dateExp, format)

Parameter Description:

dateExp– This is a mandatory parameter. It represents a valid date-time expression.

format – It’s an optional arameter that specifies the date and time format. The available return date and time formats are –

  • 0 = vbGeneralDate – This is the default format value (date format: mm/dd/yyyy and time if specified: hh:mm:ss PM/AM).
  • 1 = vbLongDate (date: weekday, monthname, year)
  • 2 = vbShortDate (date: mm/dd/yyyy)
  • 3 = vbLongTime (time: hh:mm:ss PM/AM)
  • 4 = vbShortTime (Return time: hh:mm)

Example:

In the below example, vbscript timeserial function returns the time for the given hours, minutes and seconds.

d=CDate("06-Jan-2021 13:45")
msgbox "Specified formated date time is " & FormatDateTime(d,1)
' OutPut (Msgbox):
' Specified formated date time is Wednesday, Jan 06, 2021
vbscript time functions - vbscript FormatDateTime
vbscript time functions – vbscript FormatDateTime

Conclusion:

Through this VBScript Date and Time Functions article, we have learned about the learn about the most important and frequently used VBScript Date Functions and VBScript Time functions, including vbscript Cdate, vbscript DateAdd, vbscript FormatDateTime function, etc. We hope this tutorial has helped a lot to brush up on your basics of VB Scripting. If you want to learn more about VBScript, please click here.

VBScript String Functions – An Excellent Guide for VBScript Tutorial 5

vbscript replace 300x118 1

VBScript Tutorial – Table of Content

VBScript Tutorial #1: Overview of VBScript Variables 

VBScript Tutorial #2: VBScript Conditional Statements and Loops

VBScript Tutorial #3: VBScript Procedures

VBScript Tutorial #4: VBScript Error Handling and Execute VBScript

VBScript Tutorial #5: VBScript String Functions

VBScript Tutorial #6: VBScript Date Functions

VBScript Tutorial #7: VBScript Time Functions

VBScript Tutorial #8: VBScript Array Functions

In this VBScript Tutorial, we are going to learn about the most important and frequently used VBScript String Functions, including vbscript InStr, vbscript StrComp, vbscript Mid function, etc. All the vbscript string functions are explained with an example.

VBScript Tutorial #5: VBScript String Functions

VBScript String Functions:

While working with string in vbscript, we can use vbscript string functions to perform important string operations such as search, replace, extract, get the length, comparisons, etc. Through the “VBScript String Functions” article, we will explain the frequently used built-in VBScript string functions with examples. 

Important VBScript String Functions – Summary: 

  • vbscript SubString – This method is used to extract characters from string based on provided criteria.  
  • vbscript InStr – Find the position of a particular expression(first occurrence) within a string.         
  • vbscript Replace – Replace some part with another string.    
  • vbscript Mid – This method is used to extract characters from string based on provided criteria.
  • vbscript Concatenation – This method is used to merge two or more string expressions.
  • vbscript Left – Extract characters from the left side.
  • vbscript StrComp – Compare two strings.
  • vbscript Trim – Remove spaces from both the sides (start and end) of a string.
  • vbscript Ltrim – This method clears the spaces from the left side from a specific string.
  • vbscript Rtrim – This method clears the spaces from the right side from a specific string.
  • vbscript UCase – Covert characters to upper case.      
  • vbscript LCase – Covert characters to lower case.
  • vbscript Length – This method is use to find and the return the length for a specific string expression.     
  • vbscript Right – Extract characters from the right side.          
  • vbscript StrReverse – Reversing of a string.

Important VBScript String Functions – Explanations: 

All the important vbscript string functions are explained in this section with real live example.

vbscript InStr:

The vbscript instr function finds the position of first occurrence of a particular expression available within a string and returns the position value.

Syntax: InStr([start,]string1,string2[,compare])

Parameter Description:

Start – This parameter defines the start position of string1 from where searching or checking the first occurrence of string2 will be started. This is an optional parameter. By default, if nothing is specified, the vbscript starts with 1st position.

String 1 – This string is to be searched for the occurrence checking of another string.

String 2 – This is the string expression to search for.

Compare – This is an optional field used to define the comparison type between binary or textual. The default value is 0. The possible values are – 

  • 0 = vbBinaryCompare – Perform a binary checking
  • 1 = vbTextCompare – Perform a textual checking

Example:

In this example of the vbscript InStr function, we are going to find and print the first occurrence of a search string.

string1 = "aabbccddee"
string2 = "bb"
nPostionOfOccurance = INSTR(1,string1,string2,1)
msgbox "Position of first occurance - " & nPostionOfOccurance
vbscript instr
vbscript string functions – vbscript instr

vbscript string Replace:

The vbscript string replaces function is used to replace the specified parts of a string with another string for a predefined number of occurrences.

Syntax: Replace(mainString,findString,replacewith[,startPos[,count[,compare]]])

Parameter Description:

mainString – This is the main string that is to be updated for the replacement.

findString – This string portion will be replaced in the main string.

replaceWith – This is the replacement string.

StartPos – This parameter defines the start position of the main string from where searching will be started. This is an optional parameter. By default, if nothing is specified, the vbscript starts with 1st position. Before the start position, all the characters will be removed.

Count – This is an optional parameter that is used to define the numbers of substitutions to be done. The default value for the count parameter is -1, which defines that there is no limitation on number of substitutions to be done.

Compare – This is an optional field used to define the comparison type between binary or textual. The default value is 0. The possible values are – 

  • 0 = vbBinaryCompare – Perform a binary checking
  • 1 = vbTextCompare – Perform a textual checking

Example:

In this example of the vbscript Replace function, we are going to replace all the occurrences of a particular string with another string.

mainString  = "aa bb cc dd bb ee"
findString  = "bb"
replaceWith = "zz"
startPos = 1
updatedString = Replace(mainString,findString,replaceWith,startPos)
msgbox "String after the replacement - " & updatedString 
vbscript replace
vbscript string functions – vbscript replace

vbscript Mid:

The vbscript Mid function returns the specified number of characters from a string.

Syntax: Mid(string,startPos[,length])

Parameter Description:

string – The specified number of characters will be extracted from this string.

startPos – It defines the start position of the characters which is going to be extracted.

length – This is an optional field that defines the length of the extracted text. If the parameter is not provided, the vbscript mid function extract the entire string after the start position.

Example:

In this example of the vbscript Mid function, we are going to extract characters of length three from position 4.

source_string  = "aaabbbcccddd"
startPos = 4
length = 3
captured_string = Mid(source_string,startPos,length)
msgbox "Extracted string of length 3 from position 4 is  - " & captured_string
vbscript mid
vbscript string functions – vbscript mid

vbscript substring:

There is no specific method with the name substring. But just like the java substring method, we can use the vbscript Mid function. 

vbscript string concatenation:

The vbscript string concatenation operator is used to add/ concrete two or more strings. The vbscript string concatenation operator is ‘&.’

Syntax: string1 & string2 & string3 …

Example:

In this example, we will add two strings using the vbscript string concatenation operator,

string1 = “abc” & “def”

After the execution, the variable string1 is going to hold the value as “abcdef”

vbscript Left function:

The vbscript Left function extracts a specified number of characters from the left side of a string.

Syntax: Left(string,length)

Parameter Description:

string – The specified number of characters will be extracted from this string from the left side.

length – It denotes the length of the characters which will be extracted from left side.

Example:

In this example of the vbscript Left function, we are going to extract characters of length three from the left side.

source_string  = "aaabbbcccddd"
length = 3
captured_string = Left(source_string,length)
msgbox "Extracted charecters from Left side  - " & captured_string
vbscript left
vbscript string functions – vbscript left

The vbscript Right function extracts a specified number of characters from the right side of a string.

Syntax: Right(string,length)

Parameter Description:

string – The specified number of characters will be extracted from this string from the right side.

length – It denotes the length of the characters which will be extracted from right side.

Example:

In this example of the vbscript Right function, we are going to extract characters of length three from the right side.

source_string  = "aaabbbcccddd"
length = 3
captured_string = Right(source_string,length)
msgbox "Extracted charecters from Right side  - " & captured_string
vbscript string functions - vbscript right
vbscript string functions – vbscript right

vbscript StrComp function:

The vbscript StrComp function is used to compare two strings and returns the result of the comparison. 

Syntax: StrComp(string1,string2[,compare])

Parameter Description:

string1 – One of the string expression parameter which required for the comparison. 

String2 – Another string expression parameter required for the comparison. 

Compare – This is an optional field used to define the comparison type between binary or textual. The default value is 0. The possible values are – 

  • 0 = vbBinaryCompare – Perform a binary checking
  • 1 = vbTextCompare – Perform a textual checking

The vbscript StrComp function can return one of the following values:

  • -1 (if string1 < string2)
  • 0 (if string1 = string2)
  • 1 (if string1 > string2)
  • Null (if string1 or string2 is Null)

Example:

In this example of the vbscript StrComp function, we are going to see the results for three different comparison conditions.

'Condition when string1<string2
string1 = "abcd"
string2 = "wxyz"
result1 = StrComp(string1,string2,vbTextCompare )

'Condition when string1 = string2
string1 = "abcd"
string2 = "abcd"
result2 = StrComp(string1,string2,vbTextCompare )

'Condition when string1>string2
string1 = "wxyz"
string2 = "abcd"
result3 = StrComp(string1,string2,vbTextCompare )
msgbox "Result 1: " & result1 & ", Result 2: " & result2 & " and Result 3: " & result3
vbscript strcomp
vbscript strcomp (vbscript string functions)

vbscript Trim function:

The vbscript Trim function is used to clear all the spaces from both the side, i.e., from the beginning and end of the string.

Syntax: Trim(string)

Parameter Description:

string – It’s a string containing spaces at the left and right sides.

Example:

In this example of the vbscript Trim function, we are going to remove the spaces from both the sides of a string.

string1 = ” aaa bbb ccc ddd “

string2 = Trim(string1)

After the execution, the string2 variable will contain the value as “aaa bbb ccc ddd,” without the spaces on the left and right sides.

vbscript Ltrim function:

The vbscript LTrim function is used to remove any spaces from the left side of the string.

Syntax: Ltrim(string)

Parameter Description:

string – It’s a string containing spaces on the left side.

Example:

In this example of the vbscript LTrim function, we are going to remove the spaces from the left side of a string.

string1 = ” aaa bbb ccc ddd “

string2 = Ltrim(string1)

After the execution, the string2 variable will contain the value as “aaa bbb ccc ddd,” without the spaces from the left side.

vbscript Rtrim function:

The vbscript RTrim function is used to remove any spaces from the right side of the string.

Syntax: Rtrim(string)

Parameter Description:

string – It’s a string containing spaces on the right side.

Example:

In this example of the vbscript RTrim function, we are going to remove the spaces from the right side of a string.

string1 = ” aaa bbb ccc ddd “

string2 = Rtrim(string1)

After the execution, the string2 variable will contain the value as “ aaa bbb ccc ddd,” without the spaces from the right side.

vbscript Uppercase i.e. vbscript UCase function:

The actual function name for vbscript Uppercase is vbscript Ucase function. The vbscript UCase function is used to convert the characters of any string(irrespective of case) into upper case characters.

Syntax: UCase(string)

Parameter Description:

string – It’s a string to convert into uppercase characters.

Example:

In this example of the vbscript UCase function, we are going to convert a string containing lower and upper cases into upper case characters.

string1 = “aBcD aabb”

string2 = Trim(string1)

After the execution, the string2 variable will contain the value as “ABCD AABB.”

vbscript Lowercase i.e. vbscript LCase:

The vbscript LCase function is used to convert the characters of any string(irrespective of case) into lower case characters.

Syntax: LCase(string)

Parameter Description:

string – It’s a string to convert into lowercase characters.

Example:

In this example of the vbscript LCase function, we are going to convert a string containing lower and upper cases into lower case characters.

string1 = “aBcD aabb”

string2 = Trim(string1)

After the execution, the string2 variable will contain the value as “abcd aabb.”

vbscript length function:

The vbscript Length function is used to find the length of a particular string. It returns the length as an integer value.

Syntax: Length(string)

Parameter Description:

string – Any string expression.

Example:

In this example of the vbscript length function, we are going to find the length of any particular string expression.

string = “aBcD aabb”

strLength = Length(string)

After the execution strLength variable will contain the length of the string as 9.

vbscript StrReverse function:

The vbscript StrReverse function is used to reversing any string.

Syntax: StrReverse(string)

Parameter Description:

string – Any string expression.

Example:

In this example of the vbscript StrReverse function, we are going to reversing the characters of a particular string.

string1 = “abcde”

string2 = Length(string1)

After the execution, the string2 variable will contain the reverse string as “edcba.”

Conclusion:

Through this VBScript String Functions article, we have learned about the important VBScript String Functions, including vbscript InStr, vbscript StrComp, vbscript Mid funtions, etc. In the next vbscript tutorial, we will explain about VBScript Date and Time functions. Please click here to get more details.