webkit: is it possible to store cookies to file and reuse it again?

Question:

is it possible to store cookies to file when you use webkit and reuse it again next time when I run my application?

Asked By: scythargon

||

Answers:

I know its old question and have been looking for the answer all over the place. Finally came up on my own after some trial and error. Hope this helps others.

from gi.repository import Soup
cookiejar = Soup.CookieJarText.new("<Your cookie path>", False)
cookiejar.set_accept_policy(Soup.CookieJarAcceptPolicy.ALWAYS)
session = WebKit.get_default_session()
session.add_feature(cookiejar)
Answered By: user871199

For those using WebKit and Gtk, change the first line from:

from gi.repository import Soup

to:

from gi.repository import Gtk, WebKit, Soup

to avoid static and dynamic conflicts.

Answered By: rise.riyo

I know I am late to this but in the latest version i.e. GTK WebKit2 4.0, this has to be done in the following way:

import gi
gi.require_version('Soup', '2.4')
gi.require_version('WebKit2', '4.0')

from gi.repository import Soup
from gi.repository import WebKit2

browser = WebKit2.WebView()

website_data_manager = browser.get_website_data_manager()
cookie_manager = website_data_manager.get_cookie_manager()
cookie_manager.set_persistent_storage('PATH_TO_YOUR/cookie.txt', WebKit2.CookiePersistentStorage.TEXT)
cookie_manager.set_accept_policy(Soup.CookieJarAcceptPolicy.ALWAYS)

I would have also liked to mention how to add or read cookies but since that wasn’t asked, I won’t.

Answered By: Blake
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.