在urllib2中使用selenium的会话cookie

Jac*_*hin 12 python cookies selenium urllib2 session-cookies

我正在尝试使用Selenium登录网站,然后使用urllib2发出RESTy请求.为了使它工作,我需要urllib2能够使用Selenium使用的相同会话.

用硒登录工作很好,我可以打电话

self.driver.get_cookies()
Run Code Online (Sandbox Code Playgroud)

我有一个selenium知道的所有cookie的列表,它最终看起来像这样的东西:

[{u'domain': u'my.awesome.web.app.local',
  u'expiry': 1319230106,
  u'name': u'ci_session',
  u'path': u'/',
  u'secure': False,
  u'value': u'9YEz6Qs9rNlONzXbZPZ5i9jm2Nn4HNrbaCJj2c%2B...'
}]
Run Code Online (Sandbox Code Playgroud)

我尝试了几种不同的方法在urllib2中使用cooky,我认为这个看起来最好:

# self.driver is my selenium driver
all_cookies = self.driver.get_cookies()
cp = urllib2.HTTPCookieProcessor()
cj = cp.cookiejar
for s_cookie in all_cookies:
    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=None
            , discard=False
            , comment=None
            , comment_url=None
            , rest=None
            , rfc2109=False
        )
    )
opener = urllib2.build_opener(cp)
response = opener.open(url_that_requires_a_logged_in_user)
response.geturl()
Run Code Online (Sandbox Code Playgroud)

它不起作用.

最后一次调用response.geturl()会返回登录页面.

我错过了什么吗?

关于如何寻找问题的任何想法?

谢谢.

ale*_*ion 14

我能够通过使用requests库来解决这个问题.我从selenium迭代了cookie,然后在一name:value对简单的字典中传递它们.

all_cookies = self.driver.get_cookies()

cookies = {}  
for s_cookie in all_cookies:
    cookies[s_cookie["name"]]=s_cookie["value"]

r = requests.get(my_url,cookies=cookies)
Run Code Online (Sandbox Code Playgroud)