使用Selenium收集的cookie的有效期格式



我正试图在硒的帮助下获得cookie,但过期值看起来很奇怪,就像'expiry': 1582237071一样。

如何将此值格式化为正常日期格式?硒饼干和用户饼干有区别吗?我使用python函数:

driver.get_cookies()

您在cookie中看到的到期值1582237071,指的是可以使用date.strftime(format)转换为人类可读格式的Epoch时间。

示例

例如,您可以在访问url时使用pickle存储cookie。http://www.google.com然后按照以下解决方案读取每个cookie的到期时间:

  • 代码块:

    import pickle
    import selenium.webdriver 
    import time
    driver = selenium.webdriver.Firefox()
    driver.get("http://www.google.com")
    pickle.dump( driver.get_cookies() , open(r'C:Utilitytestdatamy_cookies.pickle',"wb"))
    driver.quit()
    pickle_off = open(r'C:Utilitytestdatamy_cookies.pickle',"rb")
    personOut = pickle.load(pickle_off)
    print(list(personOut))
    for cookie in list(personOut):
    print(time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(cookie["expiry"])))
    
  • 控制台输出:

    [{'name': '1P_JAR', 'value': '2020-02-21-14', 'path': '/', 'domain': '.google.com', 'secure': True, 'httpOnly': False, 'expiry': 1584888349}, {'name': 'NID', 'value': '198=DCEMsfy3h6nZ0vpi6p3m3J-vVJpDlUBc7ItYE99kbFtr2fssl-1nVVXqF6joPREjrW-X8yxe5PnDqMNiVaVUd0NY8S_YOfksQdb-SzKSPUP5XumjlTjyTt_C8a5XSOmpUuXnOu-JCXHDe71fTe2KC-0kwb5B7_N7wSzM6Jrozqs', 'path': '/', 'domain': '.google.com', 'secure': True, 'httpOnly': True, 'expiry': 1598107549}]
    2020-03-22 20:15:49
    2020-08-22 20:15:49
    

您得到的值是epoch值,因此需要将其转换为正常的日期格式
你可以这样做:

time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(1582237071))

我找到了一个简单的解决方案,可以让我想要的特定cookie过期
例如:我想获取名为'__ivc'的cookie的过期时间

all_cookies=self.driver.get_cookies();
cookies_dict = {}
for cookie in all_cookies:
cookies_dict[cookie['name']] = cookie['expiry'] // You can insert expiry/value/domain/priority in the value of dctionary
print(cookies_dict)
cookie_expiry=cookies_dict.get('__ivc')
print(cookie_expiry)
print(time.strftime('%Y-%m-%d %H:%M:%S %Z', time.localtime(cookie_expiry)))

输出如下:

{'_ga': 1685026815, '__ivc': 1685026816, '_ga_MNGCCS5STP': 1685026815
}
1685026816
2023-05-25 20:30:16 India Standard Time

最新更新