HtmlAgilityPack Post Login

前端 未结 3 1606
别跟我提以往
别跟我提以往 2020-12-08 11:27

I\'m trying to login to a site using HtmlAgilityPack (site:http://html-agility-pack.net).

Now, I can\'t exactly figure out how to go about this.

I\'ve tried

3条回答
  •  失恋的感觉
    2020-12-08 11:56

    The HTML Agility Pack is used to parse HTML - you cannot use it to submit forms. Your first line of code changes the parsed nodes in memory. The second line does not post the page to the server - it loads the DOM again, but using the POST method instead of the default GET.

    It doesn't look like you need to parse the page at all at this point, since you already know the name of the control. Use the HttpWebRequest class to send a post request to the server, with the string email=acb#example.com in the request.

    Here's a sample I wrote when I needed something similar:

    /// 
    /// Append a url parameter to a string builder, url-encodes the value
    /// 
    /// 
    /// 
    /// 
    protected void AppendParameter(StringBuilder sb, string name, string value)
    {
        string encodedValue = HttpUtility.UrlEncode(value);
        sb.AppendFormat("{0}={1}&", name, encodedValue);
    }
    
    private void SendDataToService()
    {
        StringBuilder sb = new StringBuilder();
        AppendParameter(sb, "email", "hello@example.com");
    
        byte[] byteArray = Encoding.UTF8.GetBytes(sb.ToString());
    
        string url = "http://example.com/"; //or: check where the form goes
    
        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
        request.Method = "POST";
        request.ContentType = "application/x-www-form-urlencoded";
        //request.Credentials = CredentialCache.DefaultNetworkCredentials; // ??
    
        using (Stream requestStream = request.GetRequestStream())
        {
            requestStream.Write(byteArray, 0, byteArray.Length);
        }
    
        HttpWebResponse response = (HttpWebResponse)request.GetResponse();
    
        // do something with response
    }
    

提交回复
热议问题