How to handle Angularjs dropdown in selenium?

To handle an AngularJS dropdown in Selenium, you can use the Select class provided by the Selenium WebDriver API. The process is similar to handling a standard HTML dropdown (select element) with Selenium. Here’s an example using Python:

  1. First, install Selenium for Python, if you haven’t already:

BASH

pip install selenium
  1. Ensure you have the appropriate WebDriver installed (e.g., ChromeDriver for Google Chrome).
  2. Create a sample AngularJS application with a dropdown:

HTML

<!DOCTYPE html>
<html ng-app="app">
<head>
  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.2/angular.min.js"></script>
</head>
<body ng-controller="MainController">
  <select ng-model="selectedItem" ng-options="item for item in items"></select>
  <script>
    angular.module('app', [])
      .controller('MainController', function($scope) {
        $scope.items = ['Option 1', 'Option 2', 'Option 3'];
        $scope.selectedItem = $scope.items[0];
      });
  </script>
</body>
</html>

This example contains a simple AngularJS dropdown populated with options from an items array in the MainController.

  1. Create a Python script to interact with the dropdown using Selenium:

PYTHON

from selenium import webdriver
from selenium.webdriver.support.ui import Select
import time

# Set up the WebDriver (replace the path with the path to your WebDriver)
driver = webdriver.Chrome(executable_path='path/to/chromedriver')

# Open the AngularJS application
driver.get('path/to/your/angularjs/dropdown.html')

# Wait for the dropdown to load
time.sleep(2)

# Find the dropdown element
dropdown_element = driver.find_element_by_css_selector('select')

# Create a Select instance
dropdown = Select(dropdown_element)

# Interact with the dropdown (select by index, value, or visible text)
dropdown.select_by_index(1)  # Select the second option
# dropdown.select_by_value('Option 2')  # Alternative: select by value
# dropdown.select_by_visible_text('Option 2')  # Alternative: select by visible text

# Wait before closing the browser
time.sleep(5)

# Close the browser
driver.quit()

In this Python script, we import the necessary Selenium modules, set up the WebDriver, and open the AngularJS application. We then find the dropdown element, create a Select instance, and interact with the dropdown by selecting options by index, value, or visible text. Finally, we wait for a few seconds before closing the browser.

This approach should work for most AngularJS dropdowns based on the standard HTML select element. If the dropdown is implemented using custom components or third-party libraries, you may need to adjust your selectors and interaction methods accordingly.

Facebook
Twitter
LinkedIn
Pinterest

Table of Contents

Related posts