使用urllib2中的selenium的会话cookie [英] Using a session cookie from selenium in urllib2
问题描述
我尝试使用Selenium登录网站,然后使用urllib2来发出RESTy请求。为了使它工作,我需要urllib2能够使用同一会话Selenium使用。
I'm trying to use Selenium to log into a website and then use urllib2 to make RESTy requests. In order for it to work though, I need urllib2 to be able to use the same session Selenium used.
使用selenium登录工作非常好,我可以调用
The logging in with selenium worked great and I can call
self.driver.get_cookies()
并且我有一个列表,列出了所有的selenium知道的cookie,它最终看起来像这样:
and I have a list of all the cookies selenium knows about, and it ends up looking a little something like this:
[{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...'
}]
我尝试了几种不同的方式来使用uriib2中的cooky,最好的:
I've tried a few different ways to to use the cooky in urllib2, I think this one looks the best:
# 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()
它不工作。
调用response.geturl()返回登录页面。
That last call to response.geturl() returns the login page.
我缺少一些东西?
应如何寻找问题?
谢谢。
推荐答案
我能够通过使用请求
库来克服这个问题。我迭代了来自selenium的cookie,然后通过 name:value
对的简单字典传递它们。
I was able to overcome this problem by using the requests
library instead. I iterated over the cookies from selenium, and then passed them in a simple dictionary with name:value
pairs.
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)
这篇关于使用urllib2中的selenium的会话cookie的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!