Search code examples
c#xpathelement

What target to use for XPath using C#?


GOAL: when I click the button, it should go to the site I want and enter text = "test" in a textbox (id="1648750690212EditingInput").

I am able to accomplish it with the selenium extension in chrome but the target the works is xpath:idRelative and it looks like this xpath=//table[@id='gridList_headers']/thead/tr[2]/td[2]/div/div[2]/span/input.

QUESTION: How do I format the xpath in C# to accomplish this?

HTML <input type="text" class="ui-igedit-input ui-igedit-placeholder ui-iggrid-filtereditor" id="1648750690212EditingInput" placeholder="Contains..." role="textbox" aria-label="Text Editor" style="height: 100%; text-align: left;">

C#

        {
            IWebDriver driver = new ChromeDriver();
            driver.Navigate().GoToUrl("https://fakesite.com");
            driver.FindElement(By.XPath("//table[@id='gridList_headers']/thead/tr[2]/td[2]/div/div[2]/span/input")).SendKeys("test");
        }```

Solution

  • usually input fields use post requests so you can get the text with Get request and post back values to the server

    Simple GET request

    using System.Net;
    
    ...
    
    using (var wb = new WebClient())
    {
        var response = wb.DownloadString(url);
    }
    

    Simple POST request

    using System.Net;
    using System.Collections.Specialized;
    
    ...
    
    using (var wb = new WebClient())
    {
        var data = new NameValueCollection();
        data["username"] = "myUser";
        data["password"] = "myPassword";
    
        var response = wb.UploadValues(url, "POST", data);
        string responseInString = Encoding.UTF8.GetString(response);
    }
    

    and as you asked on xpath you can use it with regex and it will give you a powerfull searching on html files

    {
    // first use regex to get a part of html
    // the (.*) matches every character between the two strings
    // you get its value by using ".Groups(1).Value;"       
    var tagsac = Regex.Match(page_Source_Str, Regex.Escape("<div class=\"video-metadata video-tags-list ordered-label-list cropped\"><ul>") + "(.*)" + Regex.Escape("</ul></div>")).Groups(1).Value;
    
    // now you add the tag back to use xpath       
    var tags = "<div class=\"video-metadata video-tags-list ordered-label-list cropped\"><ul>" + tagsac + "</ul></div>";
        
    // now using xpath
    var xml = XElement.Load(new System.IO.StringReader((tags)));
    // you dig down elements to what you want    
    var k = xml.<ul>.<li>.ToList;
    
    // you get the html element value or attribute value like so    
    var Tag_List = k.FindAll(c => (XElement)c.<a>.Attributes.FirstOrDefault.Value.StartsWith("/tags")).Select(xc => xc.<a>.FirstOrDefault.Value.ToLower.Replace("-", " ")).ToList;
        }