2013-03-04 7 views
6

Io uso questo codice per accedere:Come passare i cookie a HtmlAgilityPack o 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; 
} 

poi voglio usare HtmlWeb (HtmlAgilityPack) o Webclient per analizzare il codice HTML per HtmlDocument (HtmlAgilityPack).

Il mio problema è che quando uso:

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

o

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

Il login scompaiono dunque io devo in qualche modo passare i cookie .. Qualche suggerimento?

+0

@ShahroozJefri questa non è una risposta – a1204773

+0

controllare http: // StackOverflow. it/questions/5562948/htmlagilitypack-htmldocument-cookies/5683180 # 5683180 –

risposta

17

Controllare HtmlAgilityPack.HtmlDocument Cookies

Ecco un esempio di quello che stai cercando (sintassi non testato al 100%, ho solo modificato un po 'di classe io di solito uso):

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

Ecco come lo si utilizza :

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

Nota: Se anche voi volete utilizzare POST metodo, basta creare un metodo simile a GetPage con il POST logica, refactoring del codice categoria, ecc

2

Ci sono alcune raccomandazioni qui: Using CookieContainer with WebClient class

Tuttavia, probabilmente è solo più facile da continuare ad usare il HttpWebRequest e impostare il cookie nel CookieContainer:

Il codice ha un aspetto simile al seguente:

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

La seconda cosa è che non c'è bisogno di scaricare nuovamente il sito, dal momento che è già in possesso dalla tua risposta web e si sta salvando qui:

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

si dovrebbe essere in grado di prendere solo il codice HTML e analizzarlo con l'agilità pacchetto HTML:

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

e che dovrebbe farlo ... :)

+0

Accedo al sito ma poi voglio navigare da qualche altra parte su questo sito. Effettivamente faccio una ricerca sul sito. – a1204773

+0

Devi continuare a fornire i cookie in ogni richiesta che fai. Se non si forniscono i cookie ad ogni richiesta, si presume che tu abbia effettuato il logout (la maggior parte delle informazioni di accesso è contenuta nel cookie). – Kiril

+0

per eseguire il login uso 'login();' funzione, potresti aiutarmi a creare la funzione 'getHTML (url);' perché il tuo codice precedente non è completo. – a1204773

0

Prova caching cookie dalla risposta precedente a livello locale e inviare di nuovo loro ogni richiesta Web come segue:

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