>我正在编写一个使用请求与网站交互的脚本 - 在某些时候,cookie需要转移到硒中,因为工作的一部分需要在Web驱动程序上完成。
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.cookie 不是 JSON 格式。
我的问题是如何以 JSON 格式导出 cookie?
要从scraper
转换cookies
:
cookies = [{'name': key, 'value': value} for key, value in cookiesexport.iteritems()}]
for cookie in cookies:
driver.add_cookie(cookie)