繁体   English   中英

页面需要登录时如何使用C#从网页获取HTML数据

[英]How to get HTML data from a webpage using C# when page requires log in

因此,基本上,我希望从网页上获取HTML数据-问题是访问该页面需要登录。我已经登录了浏览器(IE),但我认为我的代码未引用同一浏览器这就是为什么它需要登录。

这是我到目前为止所做的:

        public void HTMLImport(){
        string urlAddress = "https://randomWebsite.com/reports/show_report.aspx";

        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(urlAddress);
        HttpWebResponse response = (HttpWebResponse)request.GetResponse();

        if(response.StatusCode == HttpStatusCode.OK){

            Stream receiveStream = response.GetResponseStream();
            StreamReader readStream = null;

            if(response.CharacterSet == null){
                readStream = new StreamReader(receiveStream);
            }
            else{
                readStream = new StreamReader(receiveStream,Encoding.GetEncoding(response.CharacterSet));
            }
            string data = readStream.ReadToEnd();

            response.Close();
            readStream.Close();

            // This is showing the HTML data for when person is not logged in - 
            Console.WriteLine(data);



        }

您将需要使用C#代码执行登录,也许是通过使用正确的凭据将登录表单重新发布回服务器(太长时间才能在此处编写代码),然后再读回响应页面以获取会话Cookie(大多数登录功能将回复您必须包含在其他请求中的身份验证Cookie)。

没有更多的细节,很遗憾,我无法提供更多帮助。

为此,首先,您应该知道网站通常使用cookie来保存会话。

  1. 向网络服务器发送请求并获得响应,您将在响应HEAD中找到一个session_id。 (在.NET中,通常使用ASP.NET_SessionId)。
  2. 向Web服务器发送登录请求并发布用户名和密码,您应该在此请求和以下请求中添加ASP.NET_SessionId cookie。
  3. 发送带有ASP.NET_SessionId cookie的“ https://randomWebsite.com/reports/show_report.aspx ”,您将发现您已在Web服务器中登录。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM