我如何定义'HTTPCookieProcessor'全局名称?

时间:2012-03-01 17:38:36

标签: python cookies

我有这段代码:

 class API(object):

        def __init__(self):
            self.baseuri = "http://api.xxx.xxx"
            self.cj = cookielib.CookieJar()
            self.cp = urllib2.HTTPCookieProcessor(self.cj)
            self.opener = urllib2.build_opener(self.cp)

错误是:NameError: global name 'HTTPCookieProcessor' is not defined怎么回事?  P.S:

 >>> a = api.API()
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
      File "C:\Python27\lib\lib\xxxxx\api.py", line 9, in __init__
        self.cp = urllib2.HTTPCookieProcessor(self.cj)
    NameError: global name 'HTTPCookieProcessor' is not defined

1 个答案:

答案 0 :(得分:0)

当您在问题中粘贴代码时,答案可能包含在从api.py文件顶部剪切的三行中。如果我不得不猜测,我会说它们看起来像是:

import cookielib
import urllib2
# <blank line>

虽然如果import urllib2行实际上有所不同,我不会感到惊讶,这会以某种方式引起问题。如果是这种情况,请尝试用import urllib2替换您拥有的任何内容;否则你可以发布完整的文件吗?