C# HtmlAgilityPack登录后

C# HtmlAgilityPack登录后,c#,login,html-agility-pack,C#,Login,Html Agility Pack,我正在尝试使用HtmlAgilityPack(site:)登录到一个站点 现在,我不知道该怎么做 我已经尝试通过设置Html表单值 m_HtmlDoc.DocumentNode.SelectSingleNode("//input[@name='EMAIL']").SetAttributeValue("value", "myemail.com"); 然后我将表格连同 m_HtmlWeb.Load("http://example.com/", "POST"); 但这不起作用。它没有登录或其他什么

我正在尝试使用HtmlAgilityPack(site:)登录到一个站点

现在,我不知道该怎么做

我已经尝试通过设置Html表单值

m_HtmlDoc.DocumentNode.SelectSingleNode("//input[@name='EMAIL']").SetAttributeValue("value", "myemail.com");
然后我将表格连同

m_HtmlWeb.Load("http://example.com/", "POST");
但这不起作用。它没有登录或其他什么。还有其他人有其他见解吗


谢谢

HTML Agility Pack用于解析HTML-您不能使用它提交表单。您的第一行代码将更改内存中已解析的节点。第二行不会将页面发布到服务器-它会再次加载DOM,而是使用post方法而不是默认的GET

现在看起来根本不需要解析页面,因为您已经知道控件的名称。使用该类向服务器发送post请求,请求中包含字符串
email=acb#example.com

这是我在需要类似东西时写的一个示例:

/// <summary>
/// Append a url parameter to a string builder, url-encodes the value
/// </summary>
/// <param name="sb"></param>
/// <param name="name"></param>
/// <param name="value"></param>
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
}
//
///将url参数附加到字符串生成器后,url将对该值进行编码
/// 
/// 
/// 
/// 
受保护的参数(StringBuilder sb、字符串名称、字符串值)
{
字符串encodedValue=HttpUtility.UrlEncode(值);
sb.AppendFormat(“{0}={1}&”,名称,encodedValue);
}
私有void SendDataToService()
{
StringBuilder sb=新的StringBuilder();
附件参数(sb,“电子邮件”hello@example.com");
byte[]byteArray=Encoding.UTF8.GetBytes(sb.ToString());
字符串url=”http://example.com/“;//或:检查表单的位置
HttpWebRequest请求=(HttpWebRequest)WebRequest.Create(url);
request.Method=“POST”;
request.ContentType=“application/x-www-form-urlencoded”;
//request.Credentials=CredentialCache.DefaultNetworkCredentials;/??
使用(Stream requestStream=request.GetRequestStream())
{
Write(byteArray,0,byteArray.Length);
}
HttpWebResponse=(HttpWebResponse)request.GetResponse();
//做些有反应的事情
}

如果您想使用Html Agility Pack实现这一点。这是密码

CookieCollection Cookies = new CookieCollection();
            var web = new HtmlWeb();
            web.OverrideEncoding = Encoding.Default;
            web.UseCookies = true;
            web.PreRequest += (request) =>
            {
                if (request.Method == "POST")
                {
                    string payload = request.Address.Query;
                    byte[] buff = Encoding.UTF8.GetBytes(payload.ToCharArray());
                    request.ContentLength = buff.Length;
                    request.ContentType = "application/x-www-form-urlencoded";
                    System.IO.Stream reqStream = request.GetRequestStream();
                    reqStream.Write(buff, 0, buff.Length);
                }

                request.CookieContainer.Add(Cookies);

                return true;
            };

            web.PostResponse += (request, response) =>
            {
                if (request.CookieContainer.Count > 0 || response.Cookies.Count > 0)
                {
                    Cookies.Add(response.Cookies);
                }
            };

            string baseUrl = "Your Website URL";
            string urlToHit = baseUrl + "?QueryString with Login Credentials";
            HtmlDocument doc = web.Load(urlToHit, "POST");

我花了几个小时讨论这个话题,实际上找到了一个非常简单的解决方案

我有:

.net核心1.1.2

HttmlAgilityPack 1.4.9.5

登录url登录:“www.url.com/login”

urlData的url:“www.url.com/data/3”=>要获取此信息,您需要连接

这里是我所做的,它确实起了作用:

HttpClient hc = new HttpClient();

HttpResponseMessage resultLogin = await hc.PostAsync(urlLogin, new StringContent("login=myUserName&password=myPaswordValue", Encoding.UTF8, "application/x-www-form-urlencoded"));

HttpResponseMessage resultPlaylist = await hc.GetAsync(urlData);

Stream stream = await resultPlaylist.Content.ReadAsStreamAsync();

HtmlDocument doc = new HtmlDocument();

doc.Load(stream);

string webContent = doc.DocumentNode.InnerHtml;  => it works
我认为它需要先登录您的
HttpClient
,然后您才能发送所需的请求


享受

此外,如果您要下载并解析登录页面以外的页面,则可能需要在后续请求中传递从登录响应接收到的cookie。有关更多信息,请参阅。@Anders-好提示!我甚至不知道它的存在。。。谢谢罗希特·阿加瓦尔(Rohit Agarwal)和他的同学们描述了一种简单易行的方法。对于我提到的修复,只要cookies被用作会话标识符,它就可以正常工作。看看我的解决方案,我不知道这是一个什么样的答案。您假设存在用户名/密码参数,而对于大多数安全意识强的web开发人员来说,这是不存在的。我同意@maplemale!“查询字符串”上的用户凭据是个坏主意(甚至是加密的)。这不是一个通用的解决方案!