使用 HtmlAgilityPack 时如何传递密码

How to pass a password when using HtmlAgilityPack

我正在尝试读取网站的 XML 文件,我正在使用 HtmlAgilityPack。这是我使用的代码:

HtmlWeb web = new HtmlWeb( ) ;
HtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument( ) ;
doc = web.Load( "http://example.com/index.asp"  ) ;

该页面要求输入他们提供给我的密码,但我不确定如何传递密码才能进入 index.asp 页面,我将在其中阅读 XML页面链接。

示例。com/index。asp 看起来像这样:

 <form action="index.asp" method="post">
 <table>
     <tbody>
         <tr>
            <td>
                <input type="Text" name="password" value="" size="20"> 
            </td>
         </tr>
     </tbody>
 </table>
</form

如何将密码从 HtmlAgilityPack 传递到此页面? 我看到了一个使用 'HtmlWeb.PreRequest' 的示例 here,但我对这个过程并不太了解。 我看到 HtmlWeb.Load 有 7 个重载,但我不知道将保存密码的变量放在哪里。

doc = web.Load( "http://example.com/index.asp", "passwordVariable" ) ;

如果有人能指导我走上正确的研究道路,我将不胜感激。

谢谢

我想你要找的是 Post 这个页面,然后尝试访问另一个受保护的页面。网页的安全性差异很大,所有者可能正在积极尝试阻止此类编程访问。

对于使用 cookie 的简单安全站点,您可以通过请求登录页面来模仿浏览器执行的操作,使用适当的凭据(以及可能需要的任何隐藏字段)执行 POST 捕获使用提供的 cookie 创建并浏览到您要访问的页面的 cookie。

    private HttpWebRequest CreateRequest(string url, string method)
    {
        var request = (HttpWebRequest)WebRequest.Create(url);
        request.Referer = Host;
        request.UserAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/35.0.1916.153 Safari/537.36";
        request.Method = method;
        request.ContentType = "application/x-www-form-urlencoded; charset=UTF-8";

        return request;
    }

    public void Login()
    {
        byte[] bytes;
        string data;
        var SharedCookie = new CookieContainer();

        var url = "index.asp";

        try
        {
            //Start Session
            var request = CreateRequest(url, "GET");
            request.CookieContainer = SharedCookie;

            using (var tmpResponse = request.GetResponse())
            {
                //WriteResponse(tmpResponse);
                tmpResponse.Close();
            }

            //Login
            data = "password=123456";
            bytes = Encoding.UTF8.GetBytes(data);

            request = CreateRequest(url, "POST");
            request.CookieContainer = SharedCookie;

            using (var stream = request.GetRequestStream())
            {
                stream.Write(bytes, 0, bytes.Length);
            }

            using (var tmpResponse = request.GetResponse())
            {
                //WriteResponse(tmpResponse);
                tmpResponse.Close();
            }
            IsLoggedIn = true;
        }
        catch (System.Net.WebException ex)
        {
            Console.WriteLine("Web Error:" + ex.Status);
            Console.WriteLine("Url:" + url);
            Console.WriteLine(ex.Message);
        }
        catch (Exception ex)
        {
            Console.WriteLine("Url:" + url);
            Console.WriteLine(ex.Message);
        }
    }