I am trying to get urllib2 to work with PyWebKitGtk to support cookies. I think it's mostly working, but cookies aren't working between sessions. The cookies.txt file is saved, and it does look like it uses the cookies in the requests (examined in Wireshark), but the data I am seeing loaded into the browser window doesn't appear to have been using the cookies. After I log in, shut down the app, then restart it, my login session is gone.
My code
def load_uri_in_browser(self):
self.cookiejar = LWPCookieJar(config_dir + "/cookies.txt")
if os.path.isfile(self.cookiejar.filename):
self.cookiejar.load(ignore_discard=True)
#for testing, this does print cookies
for index, cookie in enumerate(self.cookiejar):
print index, ' : ', cookie
self.opener = urllib2.build_opener(
urllib2.HTTPRedirectHandler(),
urllib2.HTTPHandler(debuglevel=0),
urllib2.HTTPSHandler(debuglevel=0),
urllib2.HTTPCookieProcessor(self.cookiejar))
self.opener.addheaders = [('User-Agent', 'Mozilla/5.0 (Windows; U; Windows NT 6.1; en-GB; rv:1.9.2.13) Gecko/20101203 Firefox/3.6.13')]
self.view = webkit.WebView()
self.view.connect('navigation-policy-decision-requested', self.navigation_policy_decision_requested_cb)
self.mainFrame = self.view.get_main_frame()
self.mainFrame.load_uri("http://twitter.com")
#gtk window loaded earlier
self.window.add(self.view)
self.window.show_all()
self.window.show()
def navigation_policy_decision_requested_cb(self, view, frame, net_req, nav_act, pol_dec):
uri=net_req.get_uri()
if uri.startswith('about:'):
return False
page = self.opener.open(uri)
self.cookiejar.save(ignore_discard=True)
view.load_string(page.read(),None,None,page.geturl())
pol_dec.ignore()
return True