使用urllib2登录后提取新cookies

2024-10-01 09:17:48 发布

您现在位置:Python中文网/ 问答频道 /正文

我遇到了一个我无法解决的问题。我能够成功地获得cookies并在登录到web应用程序后使用它们。问题是web应用程序在点击几次之后就设置了新的cookies。在

如何在登录后提取或获取额外的cookies?以下是我目前为止的代码:

  def _login_to_page(self,url):
    cj = cookielib.CookieJar()
    cookiehandler = urllib2.HTTPCookieProcessor(cj)
    proxy_support = urllib2.ProxyHandler({"https" : self._proxy})
    opener = urllib2.build_opener(cookiehandler, proxy_support)
    try:
      login_post_data = {'op':'login','user':self._username,'passwd':self._password,'api_type':'json'}
      response = opener.open(str(self._path_to_login_url), urllib.urlencode(login_post_data), self._request_timeout).read()
      if response: 
        print "[+] Login successful"
        self._login_cookies = cj 
      else:
        "[-] Login has probably failed. Wrong Credentials?"

 def get_url_loggedin(self,url):
    #the variable self._login_cookies are the cookies from the previous login
    cookiehandler = urllib2.HTTPCookieProcessor(self._login_cookies)
    proxy_support = urllib2.ProxyHandler({"http" : self._proxy})
    opener = urllib2.build_opener(cookiehandler, proxy_support)
    urllib2.install_opener(opener)
    try:
      url_response = opener.open(url, None, self._request_timeout).read()
    except Exception,e:
      print "[-] Could not read page: "
      print "[??] Error: " +repr(e)

抱歉,如果我的英语有点奇怪,我不是母语。在


Tags: theselfweburlsupportreadresponselogin
1条回答
网友
1楼 · 发布于 2024-10-01 09:17:48

在应用程序设置了所需的cookie之后,您应该执行cj.save( 'cookies.txt' )将当前设置的cookie保存到该文件中,并使用cj.load('cookies.txt')在应用程序启动时加载它们。 参见cookielib documentation

相关问题 更多 >