Auto-generate XPaths using Python

In this post, we will present a way to auto-generate robust and short XPaths for the two most common HTML elements automation interacts with – buttons and input elements. We have tested this against more than 50 commonly used websites like Facebook, LinkedIn, Citibank, IRCTC, etc.


Why this post?

The foundation for robust GUI automated checks is writing good element locators. Xpath is one locator strategy used for selecting nodes from Document Object Models (DOM) like XML, HTML, etc. Generating XPaths manually is a routine and time-consuming task.

As part of simplifying our test writing process, we came up with a thought to write a utility script which will identify and auto-generate robust and simple XPaths. We started off with generating XPaths for Input and Button fields of a webpage using the general locators like id, name, class etc. The Python program in this post will demonstrate how to create XPath expressions automatically for input and button tags. Whenever there is a requirement to automate a webpage, the tester can simply run this script which would generate a bunch of XPaths without any human intervention.


What should be considered when writing an XPath?

Most of us rely on extracting the XPaths from browser plugins or tools. These tools have got limitations. One of the limitations is that they frequently produce absolute XPaths (meaning all the way from the HTML tag!) which are long and extremely flaky. Other smarter tools seem to have trouble producing unique XPaths in anything but the simplest conditions. Generally, we locate the elements using their unique attributes but some elements do not have unique attributes. Locating such elements is difficult because the XPath generated will have multiple matching elements. It is important to consider the following points while choosing an XPath. A good locator is:

  • Unique – XPath should have only one candidate element (Unique).
  • Descriptive – It is easy to identify the element easily when the XPath is descriptive.
  • Shorter in length – You will have multiple XPath options. A shorter XPath shall be selected to make it more readable.
  • Valid even after changes to a page – XPath should be selected in such a way it is valid even after changes in DOM.

Overview of our Python Utility script

We made an effort to write a script which will auto-generate XPaths for Input and Button elements in the webpage and also check for the uniqueness of the generated XPath. This will save the automation time and effort. In the coming sections, we will be talking about below items:

  • Accept a URL and parse the page content using BeautifulSoup
  • For each element, check for the existence of the attribute and guess the XPath
  • Check for uniqueness of the generated XPath
  • How we tested this utility
  • Putting it all together

Note:- If the XPath generated is not unique or if the HTML page does not have the attribute mentioned for the given tag then our script does not generate any XPaths.


Accept a URL and Parse the page content using BeautifulSoup

First, we need to import all the libraries that we are going to use. We used python module BeautifulSoup to extract and parse the HTML content.

from selenium import webdriver
from bs4 import BeautifulSoup

Our main method starts with declaring a variable which accepts the input URL of the page.

    #Get the URL and parse
    url = input("Enter URL: ")

The next step is to parse the page into a BeautifulSoup format. We used selenium’s execute_script() function to get the inner HTML of a page and return it as a string to the Python script. This method takes as a parameter a string of Javascript code that it executes inside of the browser.

    #Parsing a page with BeautifulSoup
    page = driver.execute_script("return document.body.innerHTML").encode('utf-8') #returns the inner HTML as a string
    soup = BeautifulSoup(page, 'html.parser')

For each element, check for existence of the attribute and guess the XPath

Now we have a variable, soup, containing the HTML of the page. Here’s where we can start coding the part that extracts the data. BeautifulSoup can help us get into these layers and extract the content with find_all() method. Using this method we are going to fetch all the Input and Button tags from the HTML page. We are passing the ‘soup’ as an argument for generate_xpath method.

    #execute generate_xpath
    if xpath_obj.generate_xpath(soup) is False:
        print "No XPaths generated for the URL:%s"%url

If the webpage doesn’t have any inputs and buttons it throws a print message saying that there are no tags to generate the Xpaths for this URL.

Now let us look into the generate_xpath() logic. We first initialized few list variables for element lists and attribute lists. guessable_elements lists consists of element lists and known_attribute_list consists of attribute lists. We are looping over element lists (as of now we are doing this only for input and button elements). Next for each element we will loop over the attribute lists and check for the attribute existence and then guess the XPath. Please note that we have declared the attribute lists based on the order of importance of attribute occurrence. For eg:- If ‘id‘ is not available for that element, next we are checking for ‘name‘ attribute and so on.

 def __init__(self):
        self.elements = None
        self.guessable_elements = ['input','button']
        self.known_attribute_list = ['id','name','placeholder','value','title','type','class']
 
 def generate_xpath(self,soup):
        "generate the xpath"  
        result_flag = False
        try:
            for guessable_element in self.guessable_elements:
                self.elements = soup.find_all(guessable_element)                                
                for element in self.elements:                                   
                    if (not element.has_attr("type")) or (element.has_attr("type") and element['type'] != "hidden"):
                        for attr in self.known_attribute_list:                                                      
                            if element.has_attr(attr):                                                             
                                locator = self.guess_xpath(guessable_element,attr,element)                               
                                if len(driver.find_elements_by_xpath(locator))==1:
                                    result_flag = True                                   
                                    print locator.encode('utf-8')
                                    break
                            elif guessable_element == 'button' and element.getText():                                                                  
                                button_text = element.getText()
                                if element.getText() == button_text.strip():
                                    locator = xpath_obj.guess_xpath_button(guessable_element,"text()",element.getText())
                                else:
                                    locator = xpath_obj.guess_xpath_using_contains(guessable_element,"text()",button_text.strip())
                                if len(driver.find_elements_by_xpath(locator))==1:
                                    result_flag = True                                   
                                    print locator.encode('utf-8')
                                    break        
        except Exception,e:
            print "Exception when trying to generate xpath for:%s"%guessable_element
            print "Python says:%s"%str(e)

Check for uniqueness of the generated Xpath

XPath should have only one candidate element which means the XPath should output one and only one element. To make sure that the given XPath returns a single element we are checking the length of the elements for each locator in the generate_xpath() method and if it is greater than 1 checking for another attribute. In this way we are making sure that the XPath is unique.

if len(driver.find_elements_by_xpath(locator))==1:
    result_flag = True                                   
    print locator.encode('utf-8')
    break

In the above generate_xpath() code, we are calling three different methods guess_xpath(), guess_xpath_button() and guess_xpath_using_contains(). We shall discuss in detail about these methods in below sections.

guess_xpath()
The method guess_xpath(), accepts three arguments namely tag, attr, element, and XPath is guessed based on these arguments. To handle Unicode errors due to foreign Unicode characters we used encode() and join() functions.

def guess_xpath(self,tag,attr,element):
        "Guess the xpath"
        #Class attribute returned as a unicodeded list, so removing 'u from the list and joining
        if type(element[attr]) is list:
            element[attr] = [i.encode('utf-8') for i in element[attr]]
            element[attr] = ' '.join(element[attr])
        self.xpath = "//%s[@%s='%s']"%(tag,attr,element[attr])
 
        return  self.xpath

guess_xpath_button()
We are using method guess_xpath_button() to check button.getText() condition. There will be situations, where you may not able to use any HTML property rather than text present in the element. text() function helps us to find the element based on the text present in the element. Since text() is a method, it does not need ‘@’ symbol as in case of an attribute.

def guess_xpath_button(self,tag,attr,element):
        "Guess the xpath for buttons"
        self.button_xpath = "//%s[%s='%s']"%(tag,attr,element)
 
        return  self.button_xpath

guess_xpath_using_contains()
In some cases, we may have to use ‘contains‘ function which helps the user to find the element with partial values, or dynamically changing values, ‘contains‘ verifies matches with the portion of the value for text for which we don’t need the complete text but need only part of the text. In our case, while we are testing our code with few URL’s we encountered few button tags with text having leading and trailing spaces in the text. In such cases, the XPath guessed using above guess_xpath() may not work. Hence we wrote another method called guess_xpath_using_contains() which uses ‘contains‘ function and generates XPath as shown below.

def guess_xpath_using_contains(self,tag,attr,element):
        "Guess the xpath using contains keyword"
        self.button_contains_xpath = "//%s[contains(%s,'%s')]"%(tag,attr,element)
 
        return self.button_contains_xpath

How we tested this utility

We tested this Utility with almost 50 different pages which have multiple input and button fields. We also tested with pages which don’t have any text or button fields. We came across few issues which we figured and fixed.

One of the issues we encountered is that when we ran the script in Windows, the input() command ran properly but when we ran it in Git Bash, we noticed there is a time gap in running input() command. The key to the problem is windows console prints text to the screen as soon as possible, while mingw (git bash) will wait until the application tells it to update the screen. To fix this, you can use -u flag interpreter command while running the script, which will stop python from buffering output in git bash as shown below.

   python -u xpath_util.py

Putting it all together

"""
Qxf2 Services: Utility script to generate XPaths for the given URL
* Take the input URL from the user
* Parse the HTML content using beautifilsoup
* Find all Input and Button tags
* Guess the XPaths
* To run the script in Gitbash use command 'python -u utils/xpath_util.py'
 
"""
 
from selenium import webdriver
from bs4 import BeautifulSoup
 
class Xpath_Util:
    "Class to generate the xpaths"
 
    def __init__(self):
        self.elements = None
        self.guessable_elements = ['input','button']
        self.known_attribute_list = ['id','name','placeholder','value','title','type','class']
 
    def generate_xpath(self,soup):
        "generate the xpath"  
        result_flag = False
        try:
            for guessable_element in self.guessable_elements:
                self.elements = soup.find_all(guessable_element)                                
                for element in self.elements:                                   
                    if (not element.has_attr("type")) or (element.has_attr("type") and element['type'] != "hidden"):
                        for attr in self.known_attribute_list:                                                      
                            if element.has_attr(attr):                                                             
                                locator = self.guess_xpath(guessable_element,attr,element)                               
                                if len(driver.find_elements_by_xpath(locator))==1:
                                    result_flag = True                                   
                                    print locator.encode('utf-8')
                                    break
                            elif guessable_element == 'button' and element.getText():                                                                  
                                button_text = element.getText()
                                if element.getText() == button_text.strip():
                                    locator = xpath_obj.guess_xpath_button(guessable_element,"text()",element.getText())
                                else:
                                    locator = xpath_obj.guess_xpath_using_contains(guessable_element,"text()",button_text.strip())
                                if len(driver.find_elements_by_xpath(locator))==1:
                                    result_flag = True                                   
                                    print locator.encode('utf-8')
                                    break        
        except Exception,e:
            print "Exception when trying to generate xpath for:%s"%guessable_element
            print "Python says:%s"%str(e)                                                  
 
        return result_flag
 
    def guess_xpath(self,tag,attr,element):
        "Guess the xpath based on the tag,attr,element[attr]"
        #Class attribute returned as a unicodeded list, so removing 'u from the list and joining back
        if type(element[attr]) is list:
            element[attr] = [i.encode('utf-8') for i in element[attr]]
            element[attr] = ' '.join(element[attr])                             
        self.xpath = "//%s[@%s='%s']"%(tag,attr,element[attr])
 
        return  self.xpath            
 
    def guess_xpath_button(self,tag,attr,element):
        "Guess the xpath for button tag"
        self.button_xpath = "//%s[%s='%s']"%(tag,attr,element)
 
        return  self.button_xpath
 
    def guess_xpath_using_contains(self,tag,attr,element):
        "Guess the xpath using contains function"
        self.button_contains_xpath = "//%s[contains(%s,'%s')]"%(tag,attr,element)
 
        return self.button_contains_xpath
 
 
#-------START OF SCRIPT--------
if __name__ == "__main__":
    print "Start of %s"%__file__
 
    #Initialize the xpath object
    xpath_obj = Xpath_Util()
 
    #Get the URL and parse
    url = input("Enter URL: ")
 
    #Create a chrome session
    driver = webdriver.Chrome()
    driver.get(url)
 
    #Parsing the HTML page with BeautifulSoup
    page = driver.execute_script("return document.body.innerHTML").encode('utf-8') #returns the inner HTML as a string
    soup = BeautifulSoup(page, 'html.parser')
 
    #execute generate_xpath
    if xpath_obj.generate_xpath(soup) is False:
        print "No XPaths generated for the URL:%s"%url
 
    driver.quit()

We hope this post helps you in building robust and simple XPaths using Python code for text and button fields without having to depend on any tools or browser plugins. We are also working on getting good human-friendly variable names for the generated XPaths. We will post about it shortly.

NOTE: If you found this post useful, definitely checkout our open-sourced Python test automation framework based on the page object pattern on GitHub.


References:

1. Understanding Python and Unicode
2. Scraping a JS-Rendered Page
3. Cmd and Git bash have a different result when run a Python code
4. How to flush output of print function?


Indira Nellutla

I am an engineer with about 10 years of experience in software development and testing. Prior to joining Qxf2, I worked with reputed companies like Dell and Infosys. They helped me gain good experience in the manufacturing and healthcare domains. My QA career started at Dell. I got exposure to various testing tools, processes and methodologies, got an opportunity to work on various platforms like JMS Hermes, SOAP UI, data integration, queues, etc. I chose Qxf2 because it allowed remote working. My interests are vegetable gardening using organic methods, listening to music and reading books.

Be First to Comment

Leave a Reply

Your email address will not be published.