简体   繁体   English

从selenium加载饼干与cookielib机械化

[英]loading cookies from selenium to mechanize with cookielib

I am trying to login to a website with selenium, then transfer the cookie to mechanize. 我正在尝试使用selenium登录网站,然后将cookie转移到机械化。 I have successfully logged in with selenium and saved its session cookie to a variable. 我已成功使用selenium登录并将其会话cookie保存到变量中。 The problem comes when trying to load the cookie with cookielib. 尝试使用cookielib加载cookie时出现问题。

Relevant coding: 相关编码:

.
. #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

the problem appear when setting the cookie with cj.set_cookie function, and I get the following error message 使用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'

if you print the cookies collected by Selenium and compare it to a cookie collected by mechanize/cookielib you will notice they use different formats. 如果您打印Selenium收集的cookie并将其与mechanize / cookielib收集的cookie进行比较,您会发现它们使用不同的格式。

To overcome this you can try something like this (you may need to modify it a bit, to fit your needs. but you get the general idea): 为了克服这个问题,您可以尝试这样的事情(您可能需要稍微修改一下,以满足您的需求。但是您可以得到一般的想法):

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))

A bit more fancy solution would be to iterate over the selenium cookies and make a dictionary with name : value pairs 一个更奇特的解决方案是迭代selenium cookie并创建一个名称为:值对的字典

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM