Selenium webdriver (c#) - Finding button based on attribute

后端 未结 5 1691
渐次进展
渐次进展 2021-01-13 11:22

I\'m trying to get a handle on the button below based on the attribute gl-command. I\'m aware I can find the button using a Cssselector by locator

相关标签:
5条回答
  • 2021-01-13 11:46

    use xpath for based on the attribute "gl-command"

    driver.FindElement(By.XPath(“//*[@gl-command='transaction']”)).Click();
    
    0 讨论(0)
  • 2021-01-13 11:50

    Not sure if you are asking to find a button IF it has the gl-command attribute or if the value of gl-command is some specific value so I'll answer both ways.

    Find buttons with gl-command attribute

    driver.FindElements(By.Tag("button")).Where(x => !string.IsNullOrEmpty(x.GetAttribute("gl-command")).FirstOrDefault();
    

    Can remove the FirstOrDefault() if you want all buttons with gl-command attribute.

    Find buttons with specific gl-command value

    driver.FindElements(By.Tag("button")).Where(x => !string.IsNullOrEmpty(x.GetAttribute("gl-command") && string.Compare(x.GetAttribute("gl-command"), "YOURGLCMD", StringComparison.OrdinalIgnoreCase) == 0));
    

    My closing parens might be off because I typed all this out on my phone in bed, but that's the general gist and my gf is yelling at me to go to sleep.

    0 讨论(0)
  • 2021-01-13 11:51

    If one of the class is unique you can use className

    driver.FindElement(By.ClassName("google-componentbutton"));
    // or
    driver.FindElement(By.ClassName("glmdl-button"));
    // etc
    

    If none of them unique you can use combination of all of them or some of them

    driver.FindElement(By.CssSelector(".google-componentbutton.glmdl-button.glmdl-js-button.glmdl-js-ripple-effect.google-image.gl-transaction-image"));
    // or
    driver.FindElement(By.CssSelector(".google-componentbutton.glmdl-button"));
    
    0 讨论(0)
  • 2021-01-13 11:56

    XPath would be your safest bet.

    IWebElement glButton = driver.findElement(By.xpath("//button[contains(@gl-command, 'transaction')]));
    

    There's a similar question here: http://forum.testproject.io/index.php?topic=66.0

    0 讨论(0)
  • 2021-01-13 12:03

    You can also create a custom selector with a method that returns your needed By selector for easy future use like this:

    public static By SelectorByAttributeValue(string p_strAttributeName, string p_strAttributeValue)
    {
        return (By.XPath(String.Format("//*[@{0} = '{1}']", 
                                       p_strAttributeName, 
                                       p_strAttributeValue)));
    }
    

    And use it like this:

    driver.FindElement(Selectors.SelectorByAttributeValue("data-power","5"))
    
    0 讨论(0)
提交回复
热议问题