Search code examples
pythonseleniumselenium-webdriverxpathcucumber

How to change change xpath dynamically in python


I have a feature file as:

Scenario: Verify user can select list value
Given Login user
When User clicks on column 
Then Drop down list should be visible
Then User can select any value from the drop down

In yml file I have locators as:

drop_down_list:
locator: "//div[@class='cdk-overlay-container']//div[@role='listbox']//mat-option"
strategy: XPATH

I am getting list xpath and elements xpath is like follows

//div[@class='cdk-overlay-container']//div[@role='listbox']//mat-option[1]
//div[@class='cdk-overlay-container']//div[@role='listbox']//mat-option[2]
//div[@class='cdk-overlay-container']//div[@role='listbox']//mat-option[3]
//div[@class='cdk-overlay-container']//div[@role='listbox']//mat-option[4]

.py file code is

pageName = get_node_from_description(page_name)
page_config_yaml = get_yaml_config_from(page_name)
dom_element_info = page_config_yaml.getValue(pageName, get_node_from_description(drop_down))
matching_element_on_pages = getMatchingElements(dom_element_info, browser)
dom_element_info = page_config_yaml.getValue(pageName, get_node_from_description(columnText))
matching_element_on_page = getMatchingElement(dom_element_info, browser)
value = matching_element_on_page.text
for element in matching_elements_on_page:
  val = element.text()

#Here I wanted to add [1] .[2] at the end of the dom_enlement_info

The dom_element_info is returning value like

 dom_element_info ={'locator': "//div[@class='cdk-overlay-container']//div[@role='listbox']//mat-option", 'strategy': 'XPATH'}

How to add the [1],[2] as per drop down value need


Solution

  • You can add the indexes using the following Locator Strategies:

    • Instead of:

      //div[@class='cdk-overlay-container']//div[@role='listbox']//mat-option[1]
      
    • Use:

      //div[@class='cdk-overlay-container']//div[@role='listbox']//following::mat-option[1]