Selenium: Trying to log in with cookies and get the errorMessage - “Can only set cookies for current domain” or "Unable to set Cookie"


 1 from selenium import webdriver
 2 
 3 driver = webdriver.PhantomJS(executable_path='G:/OpenSources/phantomjs-2.1.1-windows/bin/phantomjs')
 4 driver.get("http://pythonscraping.com")
 5 driver.implicitly_wait(1)
 6 print(driver.get_cookies())
 7 
 8 savedCookies = driver.get_cookies()10 
11 driver2 = webdriver.PhantomJS(executable_path='G:/OpenSources/phantomjs-2.1.1-windows/bin/phantomjs')
12 driver2.get("http://pythonscraping.com")
13 driver2.delete_all_cookies()
14 for cookie in savedCookies:
15     driver2.add_cookie(cookie)
16 
17 driver2.get("http://pythonscraping.com")
18 driver2.implicitly_wait(1)
19 print(driver2.get_cookies())

以上代碼15行報錯: "errorMessage":"Can only set Cookies for the current domain"

將15行代碼改為:

1 driver2.add_cookie({k: cookie[k] for k in ('name', 'value', 'domain', 'path', 'expiry') if k in cookie})

修改后報錯: "errorMessage":"Unable to set Cookie"

最終修改:

 1 from selenium import webdriver
 2 import time
 3 
 4 driver = webdriver.PhantomJS(executable_path='G:/OpenSources/phantomjs-2.1.1-windows/bin/phantomjs')
 5 driver.get("http://pythonscraping.com")
 6 driver.implicitly_wait(1)
 7 print(driver.get_cookies())
 8 
 9 savedCookies = driver.get_cookies()11 
12 driver2 = webdriver.PhantomJS(executable_path='G:/OpenSources/phantomjs-2.1.1-windows/bin/phantomjs')
13 driver2.get("http://pythonscraping.com")
14 driver2.delete_all_cookies()
15 for cookie in savedCookies:
16     # fix the problem-> "errorMessage":"Unable to set Cookie"
17     for k in ('name', 'value', 'domain', 'path', 'expiry'):
18         if k not in list(cookie.keys()):
19             if k == 'expiry':
20                 t = time.time()
21                 cookie[k] = int(t) # 時間戳 秒
22     # fix the problem-> "errorMessage":"Can only set Cookies for the current domain"
23     driver2.add_cookie({k: cookie[k] for k in ('name', 'value', 'domain', 'path', 'expiry') if k in cookie})
24 
25 driver2.get("http://pythonscraping.com")
26 driver2.implicitly_wait(1)
27 print(driver2.get_cookies())

 在這個例子中,第一個 webdriver獲得了一個網站,打印 cookie 並把它們保存到變量savedCookies里。第二個webdriver加載同一個網站(技術提示:必須首先加載網站,這樣Selenium 才能知道cookie 屬於哪個網站,即使加載網站的行為對我們沒任何用處),刪除所有的cookie ,然后替換成第一個webdriver得到的cookie 。當再次加載這個頁面時,兩組cookie 的時間戳、源代碼和其他信息應該完全一致。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM