【问题标题】:How to pass cookies to HtmlAgilityPack or WebClient?如何将 cookie 传递给 HtmlAgilityPack 或 WebClient?
【发布时间】:2013-02-18 20:11:32
【问题描述】:

我使用此代码登录:

CookieCollection cookies = new CookieCollection();
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("example.com");
request.CookieContainer = new CookieContainer();
request.CookieContainer.Add(cookies);
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
cookies = response.Cookies;

string getUrl = "example.com";
string postData = String.Format("my parameters");
HttpWebRequest getRequest = (HttpWebRequest)WebRequest.Create(getUrl);
getRequest.CookieContainer = new CookieContainer();
getRequest.CookieContainer.Add(cookies);
getRequest.Method = WebRequestMethods.Http.Post;
getRequest.UserAgent = "Mozilla/5.0 (Windows NT 6.2; WOW64; rv:19.0) Gecko/20100101 Firefox/19.0";
getRequest.AllowWriteStreamBuffering = true;
getRequest.ProtocolVersion = HttpVersion.Version11;
getRequest.AllowAutoRedirect = true;
getRequest.ContentType = "application/x-www-form-urlencoded";

byte[] byteArray = Encoding.ASCII.GetBytes(postData);
getRequest.ContentLength = byteArray.Length;
Stream newStream = getRequest.GetRequestStream();
newStream.Write(byteArray, 0, byteArray.Length);
newStream.Close();

HttpWebResponse getResponse = (HttpWebResponse)getRequest.GetResponse();
using (StreamReader sr = new StreamReader(getResponse.GetResponseStream(), Encoding.GetEncoding("windows-1251")))
{
        doc.LoadHtml(sr.ReadToEnd());
        webBrowser1.DocumentText = doc.DocumentNode.OuterHtml;
}

然后我想使用 HtmlWeb (HtmlAgilityPack) 或 Webclient 将 HTML 解析为 HtmlDocument(HtmlAgilityPack)。

我的问题是当我使用时:

WebClient wc = new WebClient();
webBrowser1.DocumentText = wc.DownloadString(site);

或

doc = web.Load(site);
webBrowser1.DocumentText = doc.DocumentNode.OuterHtml;

登录消失了,所以我想我必须以某种方式传递 cookie。有什么建议吗?

【问题讨论】:

标签: c# cookies httpwebrequest webclient html-agility-pack


【解决方案1】:

尝试在本地缓存来自先前响应的 cookie,然后在每个 Web 请求中重新发送它们,如下所示:

private CookieCollection cookieCollection;

...

    parserObject = new HtmlWeb
                {
                    AutoDetectEncoding = true,
                    PreRequest = request =>
                    {
                        if (cookieCollection != null)
                            cookieCollection.Cast<Cookie>()
                                .ForEach(cookie => request.CookieContainer.Add(cookie));
                        return true;
                    },
                    PostResponse = (request, response) => { cookieCollection = response.Cookies; }
                };

【讨论】:

    【解决方案2】:

    查看HtmlAgilityPack.HtmlDocument Cookies

    这是您正在寻找的示例(语法未经过 100% 测试,我只是修改了一些我常用的类):

    public class MyWebClient
    {
        //The cookies will be here.
        private CookieContainer _cookies = new CookieContainer();
    
        //In case you need to clear the cookies
        public void ClearCookies() {
            _cookies = new CookieContainer();
        }
    
        public HtmlDocument GetPage(string url) {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
            request.Method = "GET";
    
            //Set more parameters here...
            //...
    
            //This is the important part.
            request.CookieContainer = _cookies;
    
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            var stream = response.GetResponseStream();
    
            //When you get the response from the website, the cookies will be stored
            //automatically in "_cookies".
    
            using (var reader = new StreamReader(stream)) {
                string html = reader.ReadToEnd();
                var doc = new HtmlDocument();
                doc.LoadHtml(html);
                return doc;
            }
        }
    }
    

    这是你如何使用它:

    var client = new MyWebClient();
    HtmlDocument doc = client.GetPage("http://somepage.com");
    
    //This request will be sent with the cookies obtained from the page
    doc = client.GetPage("http://somepage.com/another-page");
    

    注意:如果你也想使用POST方法,只需使用POST逻辑创建一个类似于GetPage的方法,重构类等即可。

    【讨论】:

      【解决方案3】:

      这里有一些建议:Using CookieContainer with WebClient class

      但是,继续使用HttpWebRequest 并在CookieContainer 中设置cookie 可能更容易:

      代码如下所示:

       // Create a HttpWebRequest
      HttpWebRequest request = (HttpWebRequest)WebRequest.Create(getUrl);
      
      // Create the cookie container and add a cookie
      request.CookieContainer = new CookieContainer();
      
      // Add all the cookies
      foreach (Cookie cookie in response.Cookies)
      {
          request.CookieContainer.Add(cookie);
      }
      

      第二件事是您不需要再次下载该网站,因为您已经从您的网络响应中获得了它并且您将它保存在这里:

      HttpWebResponse getResponse = (HttpWebResponse)getRequest.GetResponse();
      using (StreamReader sr = new StreamReader(getResponse.GetResponseStream(), Encoding.GetEncoding("windows-1251")))
      {
              webBrowser1.DocumentText = doc.DocumentNode.OuterHtml;
      }
      

      您应该能够只获取 HTML 并使用 HTML Agility Pack 对其进行解析:

      HtmlDocument doc = new HtmlDocument();
      doc.LoadHtml(webBrowser1.DocumentText);
      

      应该这样做...... :)

      【讨论】:

      • 我登录到该站点,但随后我想在该站点的其他位置导航。其实我在网站上搜索。
      • 您必须在您提出的每个请求中继续提供 cookie。如果您没有为每个请求提供 cookie,那么它将假定您已注销(大多数登录信息包含在 cookie 中)。
      • 登录我使用login();函数,你能帮我做getHTML(url);函数吗,因为你上面的代码不完整。
      • @Loclip 好的,login(); 不是 C# 函数,getHTML 也不是,所以我帮不了你太多。我向您展示的代码应该可以帮助您弄清楚如何在您的 HttpWebRequest 中包含一个 cookie(这应该是您从页)。因此,鉴于您在问题中显示的代码以及我在答案中显示的代码,问题到底出在哪里?你必须向我提供一些有意义的信息,只是说“我试图完成你的代码,但它仍然要求我登录”并不能告诉我太多。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-06-25
      • 2013-05-09
      • 2016-03-01
      • 2016-04-12
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多