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

时间:2021-04-13 03:13:14
 from selenium import webdriver

 driver = webdriver.PhantomJS(executable_path='G:/OpenSources/phantomjs-2.1.1-windows/bin/phantomjs')
driver.get("http://pythonscraping.com")
driver.implicitly_wait(1)
print(driver.get_cookies()) savedCookies = driver.get_cookies()
driver2 = webdriver.PhantomJS(executable_path='G:/OpenSources/phantomjs-2.1.1-windows/bin/phantomjs')
driver2.get("http://pythonscraping.com")
driver2.delete_all_cookies()
for cookie in savedCookies:
driver2.add_cookie(cookie) driver2.get("http://pythonscraping.com")
driver2.implicitly_wait(1)
print(driver2.get_cookies())

以上代码15行报错: "errorMessage":"Can only set Cookies for the current domain"

将15行代码改为:

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

修改后报错: "errorMessage":"Unable to set Cookie"

最终修改:

 from selenium import webdriver
import time driver = webdriver.PhantomJS(executable_path='G:/OpenSources/phantomjs-2.1.1-windows/bin/phantomjs')
driver.get("http://pythonscraping.com")
driver.implicitly_wait(1)
print(driver.get_cookies()) savedCookies = driver.get_cookies()
driver2 = webdriver.PhantomJS(executable_path='G:/OpenSources/phantomjs-2.1.1-windows/bin/phantomjs')
driver2.get("http://pythonscraping.com")
driver2.delete_all_cookies()
for cookie in savedCookies:
# fix the problem-> "errorMessage":"Unable to set Cookie"
for k in ('name', 'value', 'domain', 'path', 'expiry'):
if k not in list(cookie.keys()):
if k == 'expiry':
t = time.time()
cookie[k] = int(t) # 时间戳 秒
# fix the problem-> "errorMessage":"Can only set Cookies for the current domain"
driver2.add_cookie({k: cookie[k] for k in ('name', 'value', 'domain', 'path', 'expiry') if k in cookie}) driver2.get("http://pythonscraping.com")
driver2.implicitly_wait(1)
print(driver2.get_cookies())

在这个例子中,第一个 webdriver获得了一个网站,打印 cookie 并把它们保存到变量savedCookies里。第二个webdriver加载同一个网站(技术提示:必须首先加载网站,这样Selenium 才能知道cookie 属于哪个网站,即使加载网站的行为对我们没任何用处),删除所有的cookie ,然后替换成第一个webdriver得到的cookie 。当再次加载这个页面时,两组cookie 的时间戳、源代码和其他信息应该完全一致。