Within the Selenium Python miscellaneous topics we shall be covering Javascript executor and some of the examples on Javascript Executor. Also we shall discuss the Chrome Options in Selenium. 

Javascript Executor and Why do we need them

Besides Selenium, all the elements in a webpage can be identified with Document Object Model provided by Javascript. Thus the Document Object Model can access all objects within a webpage.

We can spy on an element and find all the available methods in DOM for accessing the html attributes for that element. In the Console tab, if we type document. all the methods like getElementById, getElementsClassName and so on will be visible as suggestions. The below image shows some of the methods in DOM.

Thus Javascript DOM can work on any element on a webpage just like Selenium. Selenium has a method to execute Javascript code in it. There are some instances when Selenium may fail to identify an element and perform action on it. In these situations we may access the element and perform action on it with the help of DOM in Javascript.

For demonstration of Javascript Executor examples we shall be using the application with the link: https://rahulshettyacademy.com/angularpractice/

Let us now obtain the text entered in the Name edit box with the help of JavaScript Executor.

Selenium exposes the method execute_script to execute Javascript commands. The Javascript command is passed as argument to the method. To locate the Name edit box, let us first spy on the element and analyze its html code.

Now we shall move to the Console tab and shall identify the element with the help of DOM methods. To locate the Name edit box we can use the name attribute which is having name as value. DOM provided by Javascript shall identify that element with the help of its name attribute by the method document.getElementsByName. The value of the name attribute shall be passed as an argument to the method. Also, this method returns a collection of nodes with the starting index as 0.

As the Name edit box is the first matching element on the page we shall refer to that index number with [0]. On hovering over the result returned by the expression document.getElementsByName("name")[0] in Console, our desired element gets highlighted.

To obtain the value entered inside the Name edit box, we shall use the value method. So the complete Javascript command shall be: 

document.getElementsByName("name")[0].value

This entire expression shall be passed as an argument to the execute_script method. We can validate the value of the edit box in the Console with the same Javascript command. Please note the result hello returned in the Console.