当使用C#.Net(像爬虫)浏览网站的页面时,我需要保留相同的会话ID.我发现了一些方法,http嗅探器非常方便,比较我的IE浏览器发送的内容(HTTP请求)和从Web服务器接收(HTTP响应),因为重要信息在标题中(未显示)通过浏览器).请不要在服务器到浏览器之间公开的会话ID和服务器代码私有的服务器会话变量(如php)之间混淆.
WebHeaderCollection headerCollection = new WebHeaderCollection(); using (HttpWebResponse response = (HttpWebResponse)request.GetResponse()) { /* save headers */ for (int i = 0; i < response.Headers.Count; i++) { headerCollection.Add(response.Headers.AllKeys[i], response.Headers.Get(i)); } /* save cookies */ cookieContainer = new CookieContainer(); foreach (Cookie cookie in response.Cookies) { cookieContainer.Add(cookie); } }
发出其他GET或POST请求:
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri); ... /* restore PHPSESSID */ for (int i = 0; i < headerCollection.Count; i++) { string key = headerCollection.GetKey(i); if (key == "Set-Cookie") { key = "Cookie"; } else { continue; } string value = headerCollection.Get(i); request.Headers.Add(key, value); } /* restore cookies */ request.CookieContainer = cookieContainer; /* complete request */ Stream writeStream = request.GetRequestStream()
我的要求是提供更好的代码或其他想法,以保持更好的爬虫会话.
如果您创建一个cookie容器并将其分配给您的第一个和第二个请求,则无需执行从响应中复制Cookie的所有操作.
当响应设置cookie时,附加请求的cookie容器将接收并存储这些cookie.因此,在一系列请求之间维护相同的会话上下文只需维护一个cookie容器实例并将其与所有请求一起使用.
你的代码变成: -
cookieContainer = new CookieContainer(); request.CookieContainer = cookieContainer; using (HttpWebResponse response = (HttpWebResponse)request.GetResponse()) { // Do stuff with response }
然后:-
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri); ... request.CookieContainer = cookieContainer; Stream writeStream = request.GetRequestStream()