将session.cookies导出为JSON

问题描述 投票:0回答:1

我正在编写一个使用请求与网站交互的脚本 - 在某些时候,cookie需要转移到selenium,因为工作的一部分需要在webdriver上完成。

import requests
from bs4 import BeautifulSoup
import time
import cfscrape
from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
from selenium.common.exceptions import TimeoutException

scraper = cfscrape.create_scraper()


headers = {'Referer': 'https://www.off---white.com/en/GB/login'}
payload = {
    'utf8':'✓',
    'authenticity_token':'',
    'spree_user[email]': LOGIN_EMAIL,
    'spree_user[password]': PASSWORD,
    'spree_user[remember_me]': '0',
    'commit': 'Login'
}
r = scraper.post('https://www.off---white.com/en/GB/login', data=payload, headers=headers)
if r.status_code != 200:
    print('Failed to log in')
else:
    print('Successfully logged in!')

cookiesexport = scraper.cookies

driver = webdriver.Chrome()
driver.get("https://www.off---white.com/en/GB")
time.sleep(10)
driver.add_cookie(cookiesexport)
time.sleep(2)
driver.get("https://www.off---white.com/en/GB/checkout/payment")

当我运行上面的代码时,我收到以下错误:

TypeError: Object of type 'RequestsCookieJar' is not JSON serializable

我认为这是由于scraper.cookies不是JSON格式。

我的问题是如何以JSON格式导出cookie?

python python-3.x selenium-webdriver python-requests
1个回答
0
投票

要从cookies转换scraper

cookies = [{'name': key, 'value': value} for key, value in cookiesexport.iteritems()}]
for cookie in cookies:
    driver.add_cookie(cookie)
© www.soinside.com 2019 - 2024. All rights reserved.