May 15, 2020

How to perform Web Automation using Selenium and Python

Developers are emphasizing moving changes rapidly in an agile environment. They need to run correct cross-browser tests for any change that needs a modification to the front end. Although a small project can prefer manual testing, a growing number of browsers provide a case for testing automation.

This article assumes that you do not have previous knowledge of Selenium with Python training. Basic knowledge of front-end concepts such as DOM and familiarity with Python is however required.

Pre Requisites

Pip update selenium

While the Selenium installation allows the features accessible to you, additional drivers are needed to be able to communicate with a selected web browser. The drivers' software links are available for different kinds of browsers like Chrome, Edge, Firefox, and Safari. Follow the link for your choice of browser and download the compatible version of the app.

If you only intend to check Selenium locally, it would be enough to download the kit, as well as drivers. However, if you want to set Selenium up on a remote server, you'd need to install the Selenium Software in addition. Selenium Server is written in Java, and JRE 1.6 or higher is needed to be installed on your server.

Web automation with selenium and python

Once you have completed the pre-requisites section, you are ready to start your first test in Selenium with Python programming language. Webdriver and Keys classes are first imported from Selenium.

  • Webdriver manufactured from selenium
  • Import Keys from selenium.webdriver.common.keys
  • The web driver class will link you to the instance of a browser which we will cover shortly. The Keys class allows you to imitate keyboard keystrokes like special keys such as "Move" and "Home."
  • Next, build a Chrome instance with the driver's path you downloaded from the respective browser's websites. In this case, we assume the driver is in the same directory as your executing Python script.

Chrome('./chromedriver) 'Driver = webdriver.

If you're running on your local computer, this opens up a local instance of Chrome. This command allows you to conduct tests on it before you end the link to the client using the.close() process.

Next, use the driver's .get) (method to load a website. Since this method is similar to opening a Chrome window on your local computer, typing a URL and pressing Enter, you can also load a local development site. Not only does the.get() method start loading a website but it also waits for it to render fully before moving on to the next stage.

Upon successful loading of the tab, you can use the.title attribute to view the webpage 's text title. You can use the assert or if statements if you want to check whether the title contains a particular substring. Just let's print the page title for convenience.

print press.title()

Python interpreter

When you run the test on a Python interpreter, you will find that the browser window in Chrome is still active. A message on Chrome also states that it is currently controlling automated software.

Lets us add a search bar question next. First, select the HTML DOM object, enter a value and send the form by pressing the return key to simulate it. The element can be selected using its CSS class, ID, name attribute, or even the tag name. If you check the source of the search bar, you will find that this DOM element's name attribute is "q." You may then use the method.find element by name) (to select the element as follows.

= Driver.find element by name("q)

Once you have selected the DOM feature, you must first clear its contents using the.clear) (method, enter a string as its value using the.send keys) (method, and finally initate the Return key press using Keys. RETURN.

SEARCH BAR.TALL()

Search bar.send keys("make python start)

Search bar.send keys(RETURN keys)

You note in the window that the search results in the window cause a shift in the URL with that behavior. You can use the following command to validate the current Window URL.

print(driver.current url)

The following list is shown-

'https:/www.python.org/find/? q = restart+with+python&submit=

Using the.close() method to end the current session. It also disconnects user links.

Controller.close()

You have looked into the steps involved in running our first test in this example. Note that during all test stages we kept the window open to make sure you knew what was going on in the background as each order was running.

You must run multiple tests sequentially in a fully automated flow and, thus, may not be able to view each step as they occur.

Run selenium

To sum up, the discussion here's your first Python Selenium test. You can save it to a selenium test.py file and run python selenium test.py for test run.

Web driver manufactured from learn selenium with python

Import Keys from selenium.webdriver.common.keys

Chrome('./chromedriver) 'Driver = webdriver.

("https:/www.python.org")

Print(press.title)

= Driver.find element by name("q)

SEARCH BAR.TALL()

Search bar.send keys("make python start)

Search bar.send keys(RETURN keys)

print(driver.current url)

Controller.close()

Navigate via Elements in HTML DOM

Now that you have run your first Selenium test successfully with Python, let us look at various options for selecting and interacting with DOM elements. We selected the search bar in the example, and queried a string. Let's explore more on the variety. Here's the Search bar Code.

In the example, we used the.find element by name) (method, which searches within the input HTML tag for the name of the attribute. We may use other methods to scan for this word too.

CSS ID:. find element by id("field of search)

Path to DOM:. find element by xpath("/input[@id='id-search-field']")

CSS class: find element by class name("field-search)

While by design the CSS ID is unique to each element, several results can be found while searching through the class name. In fact, when searching through the element's DOM path, you may be certain that you are looking for it.

Navigate through Windows and Frames

Your web application may require multiple windows and frames for you to work with. Internet logins and file uploads are common usage cases for working on new windows. The driver's.switch to a window ( This method will help you change the active window and function into a new window on different actions. The code to a new window that switches attention is as follows.

Driver.switch to window'the window()

If the value is not stored in the target attribute, a window handle may be used that uniquely identifies all open windows on your driver. To view a list of all handles on the window, execute the code.

Print()driver.window addresses

Similarly, the.switch to frame()method allows you to move the focus to a frame within a window. The following execute to turn back to the primary window after completing the necessary actions.

Driver.switch to default()

Note that all actions in this segment change driver status and don't return anything. Hence we don't store the values in a variable and call the methods instead.

During a test work with Idle Time

While we have looked at various tests in static web applications, a single page application may require you to wait before you perform an action for a specific time period.

In Selenium with python training, there are two types of warnings: implicit and explicit waits. An explicit wait will cause your driver to wait for a specific action (like loading content using AJAX) to complete. An implied wait will cause the driver to wait for a given time.

You must use a tri-finally block for a specific wait because it can potentially make your test stuck in the worst-case scenario. Essentially, before letting go, you tell the driver to wait for a given element for a specified time.

Import By selenium.webdriver.common.by

It imports WebDriverWait from selenium.webdriver.support.ui

For the import of expected conditions as EC from selenium.webdriver.support

Aim to:

= WebDriverWait(driver, 5).until)

EC.Element presence located((By. ID, "id-of-new-element"))

)

finally:

Driver.quit()driver()

Firstly, using the Web DriverWait() function to tell the driver to wait 5 seconds. You then check the expected conditions class method for a new element to be loaded using the.presence of element located), (which you can query through By. ID.

In an implied wait, you need to use the drivers.implicitly wait) (process, and provide the driver with the number of seconds to wait.

Driver.permit wait()

Item = driver.find element by id('id-of-new-element')

Combine Selenium with Device Tests

Let's try to understand how Selenium tests can be integrated into Python unit tests. We will use the unit test module in Python for that purpose.

  • Import unless necessary
  • Web driver manufactured from selenium
  • Import Keys from selenium.webdriver.common.keys

ChromeSearchClass()unittest. TestCase():

Defigure setUp(self):

Self.driver = the Chrome(.'/chromedriver) 'webdriver.

Test search in python org(self) defect:

Driver = Driver.

("https:/www.python.org")

Driver.title: self.assertIn("Python)

Elem = driver.find element("q)

Elem.send keys("began pythoning)

Elem.send keys(RETURN keys)

Assert "https:/www.python.org/search/?q=getting+started+with+python&submit="

TearDown(self) defence:

The.driver.close()

Where == " main ":

Unity.main()

In this example, when initializing the unit test class via the. Chrome()method, you must set the driver object. The same text is put on the search bar in the single test we show, and the resulting shift in URL is contrasted with the URL shown earlier. You can also write a different browser check, and reuse the same features.

Conclusion:

I hope you reach to a conclusion about web automation using selenium and python. You can learn more from selenium online training.