user6824563
user6824563

Reputation: 815

htmlagilitypack select element and submit form

I just started working with htmlagilitypack, and I am loving it so far.

I'm trying to select a radio button and submit a form using htmlagility.

Here is the structure of the website:

<form class="picker" action="link.html" method="POST">
    <ul class="selection-list">
        <li>
            <label>
                <span class="left-side">
                    <input name="id" value="t1" type="radio">
                </span>
                <span class="right-side">
                    Test1
                </span>
            </label>
        </li>
        <li>
            <label>
                <span class="left-side">
                    <input name="id" value="t2" type="radio">
                </span>
                <span class="right-side">
                    Test2
                </span>
            </label>
        </li>
        <li>
            <label>
                <span class="left-side">
                    <input name="id" value="t3" type="radio">
                </span>
                <span class="right-side">
                    Test3
                </span>
            </label>
        </li>
    </ul>
</form>

I can get the form. Here is the code:

    HtmlWeb web = new HtmlWeb();
HtmlDocument doc = web.Load(urlAddress);

// Get the form
var form = doc.DocumentNode.SelectSingleNode("//form[@class='picker']");

How can I select, for example, the

  • Test2 and submit the form? Is it possible using htmlagilitypack or I need another library?

    Thanks

    Upvotes: 1

    Views: 2112

  • Answers (1)

    Eric
    Eric

    Reputation: 1847

    var uri = // get uri from form;
    var formVariables = new List<KeyValuePair<string, string>>();
    
    // Populate your variables here; HtmlAgilityPack is useful for propagating existing form values
    formVariables.Add(new KeyValuePair<string,string>("id","t2"));
    
    var formContent = new FormUrlEncodedContent(formVariables);
    
    using (var message = new HttpRequestMessage { Method = HttpMethod.Post, RequestUri = uri, Content = formContent })
    {
        // use HttpClient to send the message
        using (var postResponse = await client.SendAsync(message))
        {
            if (postResponse.IsSuccessStatusCode)
            {
                var stringContent = await response.Content.ReadAsStringAsync();
    
                // Do something with string content
            }
        }
    }
    

    Upvotes: 2

    Related Questions