lam du
lam du

Reputation: 1

Can't get Cookie by Selenium

I really need your help. When I'm trying to get Cookies from url its return to me is not what I was thinking about

Here is my code:

var driver = new ChromeDriver();
driver.Navigate().GoToUrl("https://m.facebook.com");
       
var cookie = driver.Manage().Cookies.AllCookies.ToString();
File.WriteAllText("cooke.txt", cookie);
        
driver.Quit();
       
Process.Start("cooke.txt");

enter image description here

Upvotes: 0

Views: 418

Answers (1)

RichEdwards
RichEdwards

Reputation: 3743

The return type for .AllCookies is a read only collection.

In order to print the content to a file, you need to iterate through the collection to write out the content.

Try something like this:

var driver = new ChromeDriver();
driver.Url = "https://www.google.com";

var cookies = driver.Manage().Cookies.AllCookies;

using (StreamWriter fs = new StreamWriter("cookies.txt", true))
{
    foreach (var cookie in cookies)
    {
        fs.WriteLine(cookie.ToString());
    }
}

For google, i get this output:

cookies.txt

That seems to match my devtools:

enter image description here

Upvotes: 1

Related Questions