Selenium webdriver get all the data attributes of an element

前端 未结 3 1783
孤城傲影
孤城傲影 2021-01-20 01:03

Using Selenium webdriver I have the following element

相关标签:
3条回答
  • 2021-01-20 01:21

    Use below Code:-

    WebElement element = "Your Element"; // Your element
    JavascriptExecutor executor = (JavascriptExecutor) driver;
    Object aa=executor.executeScript("var items = {}; for (index = 0; index < arguments[0].attributes.length; ++index) { items[arguments[0].attributes[index].name] = arguments[0].attributes[index].value }; return items;", element);
    System.out.println(aa.toString());
    

    Hope it will help you :)

    0 讨论(0)
  • 2021-01-20 01:22

    No. There is no way in Selenium WebDriver to access any attribute whose full name you don't know. You can't even enumerate over all attributes of a WebElement.

    It doesn't look like the jsonwire protocol supports this concept. The GET_ELEMENT_ATTRIBUTE command takes a list of attribute names, not a list of attribute name patterns.

    It is probable that you could query via a JavascriptExecutor and either XPath or CSS query to find all the attribute names for your element, then use that to loop over getAttribute. But if you're going to do that, you can just construct your XPath or CSS query to give you the values directly, and leave the WebElement out of it completely.

    0 讨论(0)
  • 2021-01-20 01:35

    This concept works very well. Try this!

    WebElement element = driver.findElement(By.tagName("button"));
    
    JavascriptExecutor executor = (JavascriptExecutor) driver;
    Object elementAttributes = executor.executeScript("var items = {}; for (index = 0; index < arguments[0].attributes.length; ++index) { items[arguments[0].attributes[index].name] = arguments[0].attributes[index].value }; return items;",element);
    
    System.out.println(elementAttributes.toString());
    
    0 讨论(0)
提交回复
热议问题