htmlagilitypack選擇元素並提交表單

c# html-agility-pack xpath

我剛開始使用htmlagilitypack,到目前為止我很喜歡它。

我正在嘗試選擇單選按鈕並使用htmlagility提交表單。

這是網站的結構:

<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>

我可以得到表格。這是代碼:

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

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

我該如何選擇,例如

  • Test2並提交表格?是否可以使用htmlagilitypack或我需要另一個庫?

    謝謝

  • 熱門答案

    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
            }
        }
    }
    



    許可下: CC-BY-SA with attribution
    不隸屬於 Stack Overflow
    這個KB合法嗎? 是的,了解原因
    許可下: CC-BY-SA with attribution
    不隸屬於 Stack Overflow
    這個KB合法嗎? 是的,了解原因