python 如何从dict获取cookie jar对象?

bihw5rsg  于 2022-10-30  发布在  Python
关注(0)|答案(1)|浏览(244)

对于默认的Selenium get_cookie()方法,返回字典列表,例如

current_cookies: [{'domain': '.domain.com',
                       'expiry': 1667110148,
                       'httpOnly': False,
                       'name': '_ym_isad',
                       'path': '/',
                       'sameSite': 'None',
                       'secure': True,
                       'value': '2'},
                      {'domain': '.domain.com',
                       'expiry': 1698574147,
                       'httpOnly': False,
                       'name': '_ym_uid',
                       'path': '/',
                       'sameSite': 'None',
                       'secure': True,
                       'value': '1667038148592302065'}]

我希望它是一个cookiejar对象,这样我就可以使用cookie jar使用的方法,例如cookie.expires、cookie.name等
我当前的代码当我从request.session获取cookie时一切正常-它会自动创建cookiejar对象,但当我使用Selenium时,它会创建dicts,我不知道如何将其更改为cookiejar
selenium 获取饼干代码

options = webdriver.ChromeOptions()
options.add_argument('headless')
s = Service('/Users/almeco/Downloads/projects/research/refs/seo_tools_ref/sdf/chromedriver')
driver = webdriver.Chrome(service=s, options=options)

driver.get('https://my.adcombo.com/login')
time.sleep(2)

driver.find_element(By.XPATH, '/html/body/div[2]/div/div/div[2]/div/loginform/form/input[1]').send_keys(
    'email_address')
driver.find_element(By.XPATH, '/html/body/div[2]/div/div/div[2]/div/loginform/form/input[2]').send_keys(
    'pass')
driver.find_element(By.XPATH, '/html/body/div[2]/div/div/div[2]/div/loginform/form/button').click()
time.sleep(3)
current_cookies = driver.get_cookies()

上面的代码返回的是字典列表,而不是cookie jar对象列表。我的问题是如何获取cookie jar对象而不是字典。

xyhw6mcr

xyhw6mcr1#

https://docs.python.org/3/library/http.cookiejar.html
然后是:

import http.cookiejar as cookielib

def to_cookielib_cookie(selenium_cookie):
    return cookielib.Cookie(
        version=0,
        name=selenium_cookie['name'],
        value=selenium_cookie['value'],
        port='80',
        port_specified=False,
        domain=selenium_cookie['domain'],
        domain_specified=True,
        domain_initial_dot=False,
        path=selenium_cookie['path'],
        path_specified=True,
        secure=selenium_cookie['secure'],
        expires=selenium_cookie['expiry'],
        discard=False,
        comment=None,
        comment_url=None,
        rest=None,
        rfc2109=False
    )

def put_cookies_in_jar(selenium_cookies, cookie_jar):
    for cookie in selenium_cookies:
        cookie_jar.set_cookie(to_cookielib_cookie(cookie))

相关问题