Finding page elements

Selenium has a number of functions that we can use in order to find HTML elements on a page during testing. We can search for an element using its id property, or we can use a CSS selector, or xpath. As an example of this, consider the following test:

it('should search for the term TypeScript', async () => { 
    browser.driver.get("https://www.google.com"); 
 
    await browser.driver.findElement( 
        By.id("lst-ib")).sendKeys("TypeScript"); 
    await browser.driver.findElement( 
        By.xpath('//*[@id="lst-ib"]')).sendKeys(Key.ENTER); 
 
    browser.sleep(5000); 
 
}); 

Here, we have written a test that browses to www.google.com, and then using the Selenium function named findElement. The first call to findElement uses the Selenium static function named By.id, which takes a single string argument. This will query the DOM and find an element with a matching id attribute. Once we have found this element, we can simulate entering data by using the sendKeys function, which has the effect of typing the word "TypeScript" into the search box on the Google home page.

We can also query DOM elements using xpath. The second call to findElement in our test uses the By.xpath function to query using an xpath matcher. Note that in this test, the By.id query and the By.xpath query will find the same element, which is the search input box. We can also simulate hitting the Enter key, or the Tab key by using the in-built enums for special keys, which in this case is Key.ENTER.

The final call in our test is for the browser to sleep for 5 seconds. There are a number of functions that we can use with Selenium, including moving the mouse, clicking on Elements, or pausing the browser for debugging purposes.

We can easily use the Chrome developer tools to find the correct elements to use in our Selenium tests, either by ID, by css or by xpath. If we open the developer tools using F12, and then right-click on the particular element we are interested in, we can select the Inspect menu option to open the developer tools and show the DOM tree. If we then right-click on a particular element in the DOM tree, we can use the Copy menu item, and then the Copy selector menu item to copy the css selector to the clipboard.

In a similar fashion, we can also copy the xpath selector to the clipboard, as shown in the following screenshot:

Chrome even allows us to search the DOM tree using an xpath or css selector. If we navigate to the Console tab, we can search through an xpath selector by typing in the following:

$x(" ... xpath selector goes here")

Or, we can search by css selector by typing:

$(" ... css selector goes here") 

These tools are invaluable when it comes to finding elements on our pages when we are building Selenium test suites.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.144.103.10