2013-03-04 26 views
6

tôi sử dụng mã này để đăng nhập:Làm cách nào để chuyển cookie sang HtmlAgilityPack hoặc WebClient?

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; 
} 

sau đó tôi muốn sử dụng HtmlWeb (HtmlAgilityPack) hoặc WebClient để phân tích cú pháp HTML để HtmlDocument (HtmlAgilityPack).

Vấn đề của tôi là khi tôi sử dụng:

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

hoặc

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

Tên đăng nhập biến mất vì vậy tôi nghĩ tôi bằng cách nào đó phải vượt qua cookie .. Bất kỳ lời đề nghị?

+0

@ShahroozJefri đây không phải là một câu trả lời – a1204773

+0

Kiểm tra http: // stackoverflow. com/questions/5562948/htmlagilitypack-htmldocument-cookies/5683180 # 5683180 –

Trả lời

17

Kiểm tra HtmlAgilityPack.HtmlDocument Cookies

Dưới đây là một ví dụ về bạn đang tìm kiếm gì (cú pháp không phải là 100% thử nghiệm, tôi chỉ sửa đổi một số lớp tôi thường sử dụng):

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; 
     } 
    } 
} 

Đây là cách bạn sử dụng nó :

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"); 

Lưu ý: Nếu bạn cũng muốn sử dụng POST phương pháp, chỉ cần tạo ra một phương pháp tương tự để GetPage với POST logic, cấu trúc lại các lớp vv

2

Có một số khuyến nghị ở đây: Using CookieContainer with WebClient class

Tuy nhiên, nó có thể dễ dàng hơn để tiếp tục sử dụng các HttpWebRequest và thiết lập các cookie trong CookieContainer:

Mã trông giống như sau:

// 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); 
} 

Điều thứ hai là bạn không cần phải tải các trang web một lần nữa, kể từ khi bạn đã có nó từ phản ứng web của bạn và bạn đang lưu nó ở đây:

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

Bạn nên có thể chỉ cần lấy HTML và phân tích nó với Agility Pack HTML:

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

và rằng nên làm điều đó ... :)

+0

Tôi đăng nhập vào trang web nhưng sau đó tôi muốn điều hướng đến một nơi khác trên trang web này. Trên thực tế tôi thực hiện tìm kiếm trên trang web. – a1204773

+0

Bạn phải tiếp tục cung cấp cookie theo mọi yêu cầu bạn thực hiện. Nếu bạn không cung cấp cookie với mọi yêu cầu, thì nó sẽ giả sử bạn đăng xuất (hầu hết thông tin đăng nhập được chứa trong cookie). – Kiril

+0

để làm đăng nhập tôi sử dụng 'đăng nhập();' chức năng, bạn có thể xin vui lòng giúp tôi làm cho 'getHTML (url); 'chức năng gây ra mã trên của bạn là không hoàn thành. – a1204773

0

Hãy thử bộ nhớ đệm cookie từ phản ứng trước tại địa phương và gửi lại chúng mỗi yêu cầu web như sau:

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; } 
       }; 
Các vấn đề liên quan