Selenium moving further

Today I will go over some advanced tips for how to interact with elements using javascript and combine selenium with other tools.

I. Work with web elements by JavaScript in Selenium

For more details, you can refer to this javascript-selenium-webdriver

In general there are two ways to call javascript execute from selenium:

Execute script:

element = driver.execute_script(script_string, *args)
element = driver.execute_async_script(script_string,*args)


If you want to get element value, your script should have ‘return’ like : ‘return arguments[0].shadowRoot’

  1. Find element by javascript:
  • get element by id:
  • get elements by class name:
  • get elements by selector:
Image for post
Image for post

2.Work with Shadow DOM

For more details about Shadow DOM, you can refer to this shadow dowm

In short, they use Shadow DOM to avoid conflicts by different css, interface style

→ For dealing with these when write automation scripts, we need to extract each dom from the outside to the inside


Image for post
Image for post

Or you might want to get attribute from element:

Image for post
Image for post

II. Handle basic web elements (drop-down list, radio-button)

  1. Drop-down list:

def choose_date_birthday(self, driver, index):
select_date = Select(self.start_page_elems.find_birthday_date_drop_down_elem(driver))
return select_date.select_by_index(index)

2.Radio button:

def choose_female_sex(self, driver):

III.Switch between windows

Sometimes, you need to handle multiple windows in order to execute the tests.

Selenium provide you the methods to do such things (even with iframe, or active element..)

Below is example for handling between windows for savior mobile popup.

def handle_store_button(self, browser, text_assert):
list_windows = browser.window_handles
if len(list_windows) == 2:
elif len(list_windows) == 3:
assert text_assert in browser.current_url

IV. Combine Selenium with image recognition tools (PyAutoGUI)

There are elements that selenium cannot click, in that case we need image recognition tools to deal with.

I will go through simple example with PyAutoGUI:
def test_facebook_icon(self, set_up_browser):
coords = pyautogui.locateOnScreen(‘facebook_icon.PNG’)

Notes: If you feel this blog help you and want to show the appreciation, feel free to drop by :

Image for post
Image for post

That’s will help more to create more valuable contents.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store