使用 Python 和 Selenium 保存登录 Cookie

时间:2021-01-08 13:32:19

标签: python selenium selenium-webdriver cookies session-cookies

    chrome = webdriver.Chrome(chrome_options=chrome_options,executable_path="chromedriver.exe")              
    try:
                    open(username+".json","r")
                    cookies = json.load(open(username+".json", "r"))
                    chrome.get("https://www.pandora.com/collection")
                    WebDriverWait(chrome,100).until(EC.visibility_of_all_elements_located((By.CSS_SELECTOR, 'body')))
                    chrome.delete_all_cookies()
                    for cookie in cookies:
                        chrome.add_cookie(cookie)
                    print("Loaded")   
                    chrome.get("https://www.pandora.com/collection")
                    WebDriverWait(chrome,100).until(EC.visibility_of_all_elements_located((By.CSS_SELECTOR, 'button.Avatar.Avatar--clickable')))
     except:
                    chrome.get("https://www.pandora.com/account/sign-in")
                    WebDriverWait(chrome,100).until(EC.visibility_of_all_elements_located((By.NAME,"username")))
                    chrome.find_element_by_name("username").send_keys(username)
                    chrome.find_element_by_name("password").send_keys(password)
                    chrome.find_element_by_class_name("FormButtonSubmit").click()   
                    WebDriverWait(chrome,100).until(EC.visibility_of_all_elements_located((By.CSS_SELECTOR,"body > div.Container > div > main > div > div > div.AuthLayout__container > div.AuthLayout__content > div:nth-child(1) > div:nth-child(1) > form > div:nth-child(1) > div > label > div.FormInput__container > input")))
                    WebDriverWait(chrome,100).until(EC.visibility_of_all_elements_located((By.CSS_SELECTOR, 'button.Avatar.Avatar--clickable')))
                    json.dump(chrome.get_cookies(),open(username+".json","w"))
                    print("Cookies Saved.!")
                    time.sleep(6) 

我正在使用以下代码来保存和重用登录 Cookie。它成功加载了所有 cookie,但仍然没有直接登录到域。 如果您看到任何错误,请说明

1 个答案:

答案 0 :(得分:0)

你应该使用 pickle 库来保存和加载 cookie

因此,在您登录页面后,使用此功能保存 Cookie:

Private Sub CommandButton2_Click()
    Dim rng As Range
    Set rng = ThisWorkbook.Sheets("Sheet1").UsedRange
    rng.RemoveDuplicates Columns:=1, Header:=xlYes
End Sub

并使用此函数加载它们:

def saveCookies(browser, cookiesPath):
    pickle.dump(browser.get_cookies(), open(cookiesPath,"wb"))

我在这个例子中使用了 geckodriver,你也可以在 chrome 驱动程序中做到这一点