首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >使用urllib2的Python form POST (还有保存/使用cookie的问题)

使用urllib2的Python form POST (还有保存/使用cookie的问题)
EN

Stack Overflow用户
提问于 2010-06-02 09:07:00
回答 3查看 16.8K关注 0票数 17

我正在尝试编写一个函数来发布表单数据并将返回的cookie信息保存在一个文件中,以便下次访问该页面时,cookie信息被发送到服务器(即正常的浏览器行为)。

我用curlib用C++写这段代码相对容易,但是我花了几乎一整天的时间尝试用Python语言写这段代码,使用urllib2 --仍然没有成功。

这就是我到目前为止所知道的:

代码语言:javascript
复制
import urllib, urllib2
import logging

# the path and filename to save your cookies in
COOKIEFILE = 'cookies.lwp'

cj = None
ClientCookie = None
cookielib = None


logger = logging.getLogger(__name__)

# Let's see if cookielib is available
try:
    import cookielib
except ImportError:
    logger.debug('importing cookielib failed. Trying ClientCookie')
    try:
        import ClientCookie
    except ImportError:
        logger.debug('ClientCookie isn\'t available either')
        urlopen = urllib2.urlopen
        Request = urllib2.Request
    else:
        logger.debug('imported ClientCookie succesfully')
        urlopen = ClientCookie.urlopen
        Request = ClientCookie.Request
        cj = ClientCookie.LWPCookieJar()

else:
    logger.debug('Successfully imported cookielib')
    urlopen = urllib2.urlopen
    Request = urllib2.Request

    # This is a subclass of FileCookieJar
    # that has useful load and save methods
    cj = cookielib.LWPCookieJar()


login_params = {'name': 'anon', 'password': 'pass' }

def login(theurl, login_params):
  init_cookies();

  data = urllib.urlencode(login_params)
  txheaders =  {'User-agent' : 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)'}

  try:
    # create a request object
    req = Request(theurl, data, txheaders)

    # and open it to return a handle on the url
    handle = urlopen(req)

  except IOError, e:
    log.debug('Failed to open "%s".' % theurl)
    if hasattr(e, 'code'):
      log.debug('Failed with error code - %s.' % e.code)
    elif hasattr(e, 'reason'):
      log.debug("The error object has the following 'reason' attribute :"+e.reason)
      sys.exit()

  else:

    if cj is None:
      log.debug('We don\'t have a cookie library available - sorry.')
    else:
      print 'These are the cookies we have received so far :'
      for index, cookie in enumerate(cj):
        print index, '  :  ', cookie

      # save the cookies again  
      cj.save(COOKIEFILE) 

      #return the data
      return handle.read()



# FIXME: I need to fix this so that it takes into account any cookie data we may have stored
  def get_page(*args, **query):
    if len(args) != 1:
        raise ValueError(
            "post_page() takes exactly 1 argument (%d given)" % len(args)
        )
    url = args[0]
    query = urllib.urlencode(list(query.iteritems()))
    if not url.endswith('/') and query:
        url += '/'
    if query:
        url += "?" + query
    resource = urllib.urlopen(url)
    logger.debug('GET url "%s" => "%s", code %d' % (url,
                                                    resource.url,
                                                    resource.code))
    return resource.read() 

当我尝试登录时,我传递了正确的用户名和密码。但是登录失败,并且没有保存cookie数据。

我的两个问题是:

  • 任何人都能看到登录()函数有什么问题吗?我该如何修复它?
  • 如何修改get_page()函数以利用我保存的任何cookie信息?
EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2010-06-02 09:28:38

您发布的代码中有相当多的问题。通常,你会想要构建一个自定义的打开程序,它可以处理重定向,https等,否则你会遇到麻烦。就cookie本身而言,您需要调用cookiejar上的load和save方法,并使用其中一个子类,例如MozillaCookieJarLWPCookieJar

这是我写的一个登录Facebook的类,当时我还在玩愚蠢的网页游戏。我只是修改它使用基于文件的cookiejar,而不是内存中的cookiejar。

代码语言:javascript
复制
import cookielib
import os
import urllib
import urllib2

# set these to whatever your fb account is
fb_username = "your@facebook.login"
fb_password = "secretpassword"

cookie_filename = "facebook.cookies"

class WebGamePlayer(object):

    def __init__(self, login, password):
        """ Start up... """
        self.login = login
        self.password = password

        self.cj = cookielib.MozillaCookieJar(cookie_filename)
        if os.access(cookie_filename, os.F_OK):
            self.cj.load()
        self.opener = urllib2.build_opener(
            urllib2.HTTPRedirectHandler(),
            urllib2.HTTPHandler(debuglevel=0),
            urllib2.HTTPSHandler(debuglevel=0),
            urllib2.HTTPCookieProcessor(self.cj)
        )
        self.opener.addheaders = [
            ('User-agent', ('Mozilla/4.0 (compatible; MSIE 6.0; '
                           'Windows NT 5.2; .NET CLR 1.1.4322)'))
        ]

        # need this twice - once to set cookies, once to log in...
        self.loginToFacebook()
        self.loginToFacebook()

        self.cj.save()

    def loginToFacebook(self):
        """
        Handle login. This should populate our cookie jar.
        """
        login_data = urllib.urlencode({
            'email' : self.login,
            'pass' : self.password,
        })
        response = self.opener.open("https://login.facebook.com/login.php", login_data)
        return ''.join(response.readlines())

test = WebGamePlayer(fb_username, fb_password)

设置用户名和密码后,您应该会看到一个文件facebook.cookies,其中包含您的cookies。在实践中,您可能希望修改它以检查是否有活动的cookie并使用它,如果访问被拒绝,则再次登录。

票数 30
EN

Stack Overflow用户

发布于 2010-12-06 05:29:32

如果你很难让POST请求正常工作(就像我使用登录表单一样),那么将Live HTTP headers扩展快速安装到Firefox (http://livehttpheaders.mozdev.org/index.html)绝对是值得的。除了其他功能之外,这个小扩展还可以显示手动登录时发送的确切POST数据。

在我的例子中,我已经用头撞了几个小时的墙,因为网站坚持要一个额外的带有'action=login‘的字段(哇!)。

票数 2
EN

Stack Overflow用户

发布于 2012-08-24 11:20:23

请在保存cookie时使用ignore_discardignore_expires,在我的情况下它保存OK。

代码语言:javascript
复制
self.cj.save(cookie_file, ignore_discard=True, ignore_expires=True)
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/2954381

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档