How to get the value of an attribute using XPath

后端 未结 4 1124
陌清茗
陌清茗 2020-12-10 16:27

I have been testing using Selenium WebDriver and I have been looking for an XPath code to get the value of the attribute of an HTML element as part of my regression testing.

相关标签:
4条回答
  • 2020-12-10 16:34

    You can use the getAttribute() method.

    driver.findElement(By.xpath("//div[@class='firstdiv']")).getAttribute("alt");
    
    0 讨论(0)
  • 2020-12-10 16:46

    Selenium Xpath can only return elements. You should pass javascript function that executes xpaths and returns strings to selenium.

    I'm not sure why they made it this way. Xpath should support returning strings.

    0 讨论(0)
  • 2020-12-10 16:51

    Using C#, .Net 4.5, and Selenium 2.45

    Use findElements to capture firstdiv elements into a collection.

    var firstDivCollection = driver.findElements(By.XPath("//div[@class='firstdiv']"));
    

    Then iterate over the collection.

            foreach (var div in firstDivCollection) {
                div.GetAttribute("alt");
            }
    
    0 讨论(0)
  • 2020-12-10 16:56

    Just use executeScript and do XPath or querySelector/getAttribute in browser. Other solutions are wrong, because it takes forever to call getAttribute for each element from Selenium if you have more than a few.

      var hrefsPromise = driver.executeScript(`
            var elements = document.querySelectorAll('div.firstdiv');
            elements = Array.prototype.slice.call(elements);
            return elements.map(function (element) {
                  return element.getAttribute('alt');
            });
      `);
    
    0 讨论(0)
提交回复
热议问题