【发布时间】:2011-10-20 21:43:19
【问题描述】:
我正在尝试让 urllib2 与 PyWebKitGtk 一起支持 cookie。我认为它大部分都在工作,但 cookie 在会话之间不起作用。 cookies.txt 文件已保存,它看起来确实在请求中使用了 cookie(在 Wireshark 中检查),但我看到加载到浏览器窗口中的数据似乎并未使用 cookie。登录后,关闭应用程序,然后重新启动,我的登录会话就消失了。
我的代码
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
【问题讨论】: