我正在尝试编写一个函数来发布表单数据并将返回的cookie信息保存在一个文件中,以便下次访问该页面时,cookie信息将被发送到服务器(即正常的浏览器行为)。
我使用curlib在C ++中相对容易地编写了这个,但是花了将近一整天的时间尝试使用urllib2在Python中编写它 - 但仍然没有成功。
这是我到目前为止所做的:
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数据。
我的两个问题是:
答案 0 :(得分:30)
您发布的代码存在很多问题。通常,您需要构建一个可以处理重定向,https等的自定义开启工具,否则您将遇到麻烦。至于cookie本身,您需要在cookiejar
上调用加载和保存方法,并使用其中一个子类,例如MozillaCookieJar
或LWPCookieJar
。
这是我写一篇登录Facebook的课程,当时我正在玩愚蠢的网页游戏。我只是修改它以使用基于文件的cookiejar,而不是内存中的。
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
,其中包含您的Cookie。在实践中,您可能希望修改它以检查您是否有活动cookie并使用它,然后在访问被拒绝时再次登录。
答案 1 :(得分:2)
如果你很难让你的POST请求工作(就像我使用登录表单一样),那么快速安装Live HTTP标头扩展到Firefox是值得的(http://livehttpheaders.mozdev.org/的index.html)。除其他外,这个小扩展可以显示手动登录时发送的确切POST数据。
在我的情况下,我把头撞在墙上好几个小时,因为该网站坚持使用'action = login'(doh!)来增加一个字段。
答案 2 :(得分:1)
请在保存Cookie时使用ignore_discard
和ignore_expires
,在我的情况下保存确定。
self.cj.save(cookie_file, ignore_discard=True, ignore_expires=True)