How to pass cookies to HtmlAgilityPack or WebClient?

c# cookies html-agility-pack httpwebrequest webclient

Question

I log in with this code:

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

then I want to parse the HTML into an HTML document using HtmlWeb (HtmlAgilityPack) or Webclient (HtmlAgilityPack).

The issue I have is that when I use:

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

or

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

The login disappears, thus I believe I must pass the cookies in some way. Any recommendations?

1
10
3/4/2013 6:35:16 PM

Accepted Answer

Verify Cookies from HTMLAgilityPack.HtmlDocument

A sample of what you're searching for is as follows:

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

Here's how to apply it:

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

Note: If you wish to usePOST just develop a procedure that is equivalent toGetPage using thePOST logic, class refactoring, etc.

19
5/23/2017 12:10:48 PM

Popular Answer

Here are a few suggestions: Using the WebClient class and the CookieContainer

But it's probably simply simpler to continue utilizing theHttpWebRequest such that it is placed in theCookieContainer :

This is how the code appears:

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

The second is that because you already have the site downloaded from your web response and are keeping it here, you don't need to do it again.

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

With the HTML Agility Pack, you should be able to just take the HTML and parse it:

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

And that ought to finish it.



Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow