Home > Net >  Getting attribute value using Selenium
Getting attribute value using Selenium

Time:07-22

This is my html page i want to parse:

<html lang="en-US" data-ismobile="false">
    <body ond="return false;" onselect="return false;" textmenu="return false">
        <div id="wrap">
            <form id="frm1" method="post">
                <input name="Token" type="hidden" value="XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX">
                <input type="hidden" name="cate" value="0">
                <input type="hidden" name="sub" value="7">
            </form>
            <form id="frm2" method="post">
                <input name="Token" type="hidden" value="YYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYY">
                <input type="hidden" name="cate" value="0">
                <input type="hidden" name="sub" value="7">
            </form>
        </div>
    </body>
</html>

I am trying to get name & value attributes from form frm1

So far i have come up with following code:

IWebElement _frm1 = webDriver.FindElement(By.Id("frm1")); //this should find me a correct form
token_frm1 = _frm1 .GetAttribute("value"); //this i know is inccorect 

CodePudding user response:

form node has neither @name nor @value. Try to get attribute values from child inputnode

IWebElement _frm1 = webDriver.FindElement(By.Id("frm1"));
IWebElement _input = _frm1.FindElement(By.Name("Token"));
token_frm1 = _input .GetAttribute("value");

CodePudding user response:

The name and value attributes are within the <input> tag. To extract the value of the name and value attribute you can use the following Locator Strategies:

  • Extract value of name attribute:

    Console.WriteLine(driver.FindElement(By.XPath("//form[@id='frm1']//input")).GetAttribute("name"));
    
  • Extract value of value attribute:

    Console.WriteLine(driver.FindElement(By.XPath("//form[@id='frm1']//input")).GetAttribute("value"));
    

Update

There are multiple <input> elements with name and value attribute. So to extract the value of the name and value attribute from <frm1> you can use the following Locator Strategies:

  • Extract value of name attribute:

    IList < IWebElement > elements = driver.FindElements(By.XPath("//form[@id='frm1']//input"));
    foreach(IWebElement e in elements) {
        System.Console.WriteLine(e.GetAttribute("name"));
    
  • Extract value of value attribute:

    IList < IWebElement > elements = driver.FindElements(By.XPath("//form[@id='frm1']//input"));
    foreach(IWebElement e in elements) {
        System.Console.WriteLine(e.GetAttribute("value"));
    
  • Related