How can I write Python selenium test for PrimeFaces?

I am trying to write a Selenium test but the issue is I have learned that the page is generated with PrimeFaces, thus the element IDs randomly change from time to time. Not using IDs is not very reliable. Is there anything I can do?

1 answer

  • answered 2019-12-09 13:42 alecxe

    Not having meaningful stable IDs is not a problem, as there are always alternative ways to locate elements on a page. Just to name a few options:

    • partial id matches with XPath or CSS, e.g.:

       # contains
       driver.find_element_by_css_selector("span[id*=customer]")
       driver.find_element_by_xpath("//span[contains(@id, 'customer')]")
      
       # starts with
       driver.find_element_by_css_selector("span[id^=customer]")
       driver.find_element_by_xpath("//span[starts-with(@id, 'customer')]")
      
       # ends with
       driver.find_element_by_css_selector("span[id$=customer]")
      
    • classes which refer/tell some valuable information about the data types ("data-oriented locators"):

       driver.find_element_by_css_selector(".price")
       driver.find_element_by_class_name("price")
      
    • going sideways from a label:

       # <label>Price</label><span id="65123safg12">10.00</span>
       driver.find_element_by_xpath("//label[.='Price']/following-sibling::span")
      
    • links by link text or partial link text:

       driver.find_element_by_link_text("Information")
       driver.find_element_by_partial_link_text("more")
      

    And, you can, of course, get creative and combine them. There are more:

    There is also this relevant thread which goes over best practices when choosing a method to locate an element on a page: