Search code examples
javaseleniumselenium-webdriverappium-android

How to locate a button with a dynamicID


I am automating an Android app using Appium where we need to click a button with a dynamic ID. Either the button has ID "PROFILEBUTTON" or ID "PROFILEMAILBUTTON". Apart from co-ordinates, what else can be used to automate clicking this button?


Solution

  • To identify an element with dynamic ID either PROFILEBUTTON or PROFILEMAILBUTTON you can use cssSelector with the following wildcards :

    • ^ : To indicate an attribute value starts with

    • $ : To indicate an attribute value ends with

    So the most granular locator would include the strategy to lookout for the initial letters i.e. PROFILE and the ending letters i.e. BUTTON and should be :

    driver.findElement(By.cssSelector("[id^='PROFILE'][id$='BUTTON']"));
    

    Update

    As per your comment update, you can use either of the equivalent xpath as follows :

    driver.findElement(By.xpath("//*[contains(@resource-id,'profileMail') and contains(@resource-id,'Button')]"));
    //or
    driver.findElement(By.xpath("//*[contains(@resource-id,'profileMailButton') or contains(@resource-id,'profileMailPremiumButton')]"));