基本上我有一个程序可以使用请求库及其发布请求。我想在调用post请求后获取会话的cookie并将它们加载到webdriver中。我正在考虑使用硒和铬二元,但我很困惑如何去做。
基本上我到目前为止。
import requests
url=www.storeUrl.com
session=requests.Session()
data={'utf8': '%E2%9C%93',
'auth': 'oBLLJkW+A2plgT1lUJeKXq7DdqJSniGnZhnSmpuAQOE%3D',
'stat': 'null',
'user': 'zdw7287'}
session.cookies.clear()
response=session.post(url,data=data)
storeResponse=session.request('get','http://www.storeUrl.com')
print storeResponse.cookies
类的requests.cookies.RequestsCookieJar'>曲奇_store_session = BAh7CUkiD3Nlc3Npb25faWQGOgZFRkkiJTBiYmY4MmEzNmRmMjZkMjNhZDdiODg4NWVmYWQ5Y2IzBjsAVEkiB3RqBjsARnsLSSIHcDAGOwBGSXU6CVRpbWUNte4cgFPoSgUKOgtAX3pvbmVJIghFU1QGOwBUOg1uYW5vX251bWkCGgE6DW5hbm9fZGVuaQY6DXN1Ym1pY3JvIgcoIDoLb2Zmc2V0af6wuUkiB3AxBjsARjBJIgdwMgY7AEYwSSIHY3MGOwBGMEkiB2NjBjsARjBJIghpcHMGOwBGWwYiETI0LjkxLjIyNi4zNkkiCWNhcnQGOwBGewdpAph7aQY6C2Nvb2tpZUkiHTEgaXRlbS0tJDM2LS0zMTY0MCwxMjY0MwY7AFRJIhBfY3NyZl90b2tlbgY7AEZJIjFxNHI4QWFUQWNWaXZmY2xIVlNPcHRQeUk2ODF2NTVhbm9pREE1YWFSOHpNPQY7AEY%3D - eea073c1f0a4fd19163e39536e75eed04ab788f9为www.storeUrl.com/>]>
如何将此cookie加载到硒中?任何帮助将不胜感激。
答案 0 :(得分:2)
Selenium
内置了add_cookie方法,用于向当前会话添加Cookie:
In [4]: browser.add_cookie??
Type: instancemethod
String form: <bound method WebDriver.add_cookie of <selenium.webdriver.chrome.webdriver.WebDriver (session="8b6e7ab963b91b5050fa1b8ef2bd7bfa")>>
File: /usr/local/lib/python2.7/site-packages/selenium/webdriver/remote/webdriver.py
Definition: browser.add_cookie(self, cookie_dict)
Source:
def add_cookie(self, cookie_dict):
"""
Adds a cookie to your current session.
:Args:
- cookie_dict: A dictionary object, with required keys - "name" and "value";
optional keys - "path", "domain", "secure", "expiry"
Usage:
driver.add_cookie({'name' : 'foo', 'value' : 'bar'})
driver.add_cookie({'name' : 'foo', 'value' : 'bar', 'path' : '/'})
driver.add_cookie({'name' : 'foo', 'value' : 'bar', 'path' : '/', 'secure':True})
"""
self.execute(Command.ADD_COOKIE, {'cookie': cookie_dict})
基本上,您需要将带有Cookie的dict
传递给add_cookie
方法,并使用Cookie session.cookies.get_dict()
返回dict
:
driver.add_cookie(session.cookies.get_dict())
示例:
Selenium
添加Cookie:https://stackoverflow.com/a/15058521/2517622 requests
获取Cookie:https://stackoverflow.com/a/25092059/2517622 答案 1 :(得分:0)
from selenium import webdriver
driver = webdriver.Firefox()
cookeis = storeResponse.cookies # cookiejar like in question
driver.get('<your url>') # catch InvalidCookieDomainException without in
for key in cookies.keys():
# print({name: key, value: cookies[key]}) # just print
driver.add_cookie({'name': key, 'value': cookies[key]})