c# - 使用 HttpWebRequest 登录到 Https 网站后的 Htmlagilitypack?

标签 c# https httpwebrequest html-agility-pack

我想解析一些 html 网站,例如 pluralsight,例如(https://app.pluralsight.com/id ?),那么我如何首先以编程方式登录网站(不使用网络浏览器控件)然后调用另一个 url(例如:Pluralsight)并获得响应并使用 Htmlagility 包进行解析。

但是我已经写了一个登录代码,但是我不知道下一步。

public class Login
{
    private CookieContainer Cookies = new CookieContainer();



public void SiteLogin(string username, string password)
{
    Uri site = new Uri("https://app.pluralsight.com/id?");

    HttpWebRequest wr = (HttpWebRequest)WebRequest.Create(site);
    wr.Method = "Post";
    wr.ContentType = "application/x-www-form-urlencoded";
    wr.Referer = "https://app.pluralsight.com/id?";
    wr.CookieContainer = Cookies;
    var parameters = new Dictionary<string, string>{
    {"realm", "vzw"},
    {"goto",""},
    {"gotoOnFail",""},
    {"gx_charset", "UTF-8"},
    {"rememberUserNameCheckBoxExists","Y"},
    {"IDToken1", username},
    {"IDToken2", password}
};

    string input = string.Empty;
    using (var requestStream = wr.GetRequestStream())
    using (var writer = new StreamWriter(requestStream, Encoding.UTF8))
        writer.Write(ParamsToFormEncoded(parameters));

    using (var response = (HttpWebResponse)wr.GetResponse())
    {

        if (response.StatusCode == HttpStatusCode.OK)
        {
            //but I do not know the next step.
        }
    }
}

private string ParamsToFormEncoded(Dictionary<string, string> parameters)
{
    return string.Join("&", parameters.Select(kvp => Uri.EscapeDataString(kvp.Key).Replace("%20", "+")
    + "=" + Uri.EscapeDataString(kvp.Value).Replace("20%", "+")
    ).ToArray());
}
}

最佳答案

您必须通过 HttpWebResponse.GetResponseStream 获取响应流然后通过 HtmlDocument 的 Load 方法加载文档。

var doc = new HtmlAgilityPack.HtmlDocument();
doc.Load(response.GetResponseStream());
//further processing...

关于c# - 使用 HttpWebRequest 登录到 Https 网站后的 Htmlagilitypack?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37385103/

相关文章:

c# - 正则表达式挑战 : Modify this line of C#

azure - azure cloudapp.net 的 SSL 证书

c# - 在 C# 中使用 POST/httpwebrequest 上传 zip 文件

c# - 如何为 HttpWebRequest 定义更积极的超时?

http - Network/Golang - "GET"请求剖析

http - 当content-type header为image/jpeg时,HTTP响应的内容数据格式是什么?

c# - 如何使用 iTextSharp 转换为 PDF

c# - 保存发送给机器人的用户消息并将完成的表格发送给其他用户

c# - WPF 绑定(bind)到子集合

c# - 使用 .net WebClient 访问交叉签名的 SSL 服务