我想听听您关于如何有效存储 cookie 的建议,这些 cookie 将在类中由其他函数使用。我当前的代码如下所示:
class SomeClass:
def __init__(self, username, password):
self.logged_in = False
self.username = username
self.password = password
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor())
urllib2.install_opener(opener)
def _login(self, username, password):
if not self.logged_in:
params = urllib.urlencode({'username': username, 'password': password})
conn = urllib2.Request('http://somedomain.com/login', params)
urllib2.urlopen(conn)
self.logged_in = True
def _checkLogin(self):
if not self.logged_in:
self._login(self.username, self.password)
def doSomeStuffThatRequireCookies(self):
self._checkLogin()
data = urllib2.urlopen(conn).read()
return data
尽管上面的示例有效,但如果我不想使用 cookie 发出请求,我必须构建自定义 Request(),并且我确信一定有更好、更优雅的方法来执行此操作。
谢谢。
首先,正如 jathanism 所注意到的,您实际上并没有安装 cookie jar。
import cookielib
...
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cookielib.CookieJar()))
然后, urllib2.install_opener(opener) 将全局安装 opener(!),您不需要这样做。删除 urllib2.install_opener(opener)。
对于非 cookie 请求,请执行以下操作:
您不需要构建 Request 对象,只需使用 url 和 params 调用 urlopen 即可:
params = urllib.urlencode({'username': username, 'password': password})
urllib2.urlopen('http://somedomain.com/login', params)
对于 cookie 请求,请使用 opener 对象:
self.opener.urlopen(url, data)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)