从selenium加载饼干与cookielib机械化

时间:2013-11-30 21:55:23

标签: python cookies selenium mechanize cookielib

我正在尝试使用selenium登录网站,然后将cookie转移到机械化。我已成功使用selenium登录并将其会话cookie保存到变量中。尝试使用cookielib加载cookie时会出现问题。

相关编码:

.
. #loging in to website with selenium
.
cookie = browser.get_cookies()   #save the session cookie from selenium to variable "cookie"
.
. #starting up mechanize
.
cj = cookielib.LWPCookieJar() 
.
.
.
cj.set_cookie(cookie) #load cookie from selenium

使用cj.set_cookie函数设置cookie时出现问题,我收到以下错误消息

File "..../cookielib.py", line 1627, in set_cookie
if cookie.domain not in c: c[cookie.domain] = {}
AttributeError: 'list' object has no attribute 'domain'

1 个答案:

答案 0 :(得分:7)

如果您打印Selenium收集的cookie并将其与mechanize / cookielib收集的cookie进行比较,您会发现它们使用不同的格式。

为了克服这个问题,您可以尝试这样的事情(您可能需要稍微修改一下,以满足您的需求。但是您会得到一般的想法):

cj = cookielib.LWPCookieJar()

for s_cookie in cookie:
    cj.set_cookie(cookielib.Cookie(version = 0, name = s_cookie['name'], value = s_cookie['value'], port = '80', port_specified = False, domain = s_cookie['domain'], domain_specified = True, domain_initial_dot = False, path = s_cookie['path'], path_specified = True, secure = s_cookie['secure'], expires = s_cookie['expiry'], discard = False, comment = None, comment_url = None, rest = None, rfc2109 = False))

更奇特的解决方案是迭代selenium cookies并制作一个名称为:value pairs的字典