Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set cookies in phantomjs using selenium with python?

enter image description here

It raise an error message said "Can only set Cookies for the current domain",but all I did is just put the old cookies in.Sometime I add the 'correct' domain,it will raise error Message "Unable to set Cookie". And I tested it in Firefox,Firefox also cant work.

from selenium import webdriver
driver = webdriver.PhantomJS(executable_path=phantompath)
driver.get('http://stackoverflow.com/')
driver.get_screenshot_as_file('1.png')
cookies = driver.get_cookies()
driver.delete_all_cookies()
driver.get_cookies()
for cookie in cookies:
    driver.add_cookie(cookie)
like image 486
Louise Avatar asked Jun 01 '16 20:06

Louise


People also ask

How do I use PhantomJS in Python?

To use the PhantomJS webdriver, all you need to do is change it to PhantomJS(). Then will This will work with both Python 2.7 and Python 3. On Windows, the path should be changed to the location of your phantomjs installation.

Does Selenium support PhantomJS?

Selenium considers PhantomJS as deprecated, so you need to us either Chrome or Firefox in headless mode.


2 Answers

The PhantomJS driver doesn't support all the keys from the cookie dictionary. One way to overcome this issue is to select the keys:

from selenium import webdriver

driver = webdriver.PhantomJS()
driver.get('http://stackoverflow.com/')

cookies = driver.get_cookies()

driver.delete_all_cookies()

for cookie in cookies :
    driver.add_cookie({k: cookie[k] for k in ('name', 'value', 'domain', 'path', 'expiry')})
like image 121
Florent B. Avatar answered Oct 13 '22 20:10

Florent B.


You need to change the domain parameter for each cookie. The domain field must be formatted like this:

driver = webdriver.PhantomJS()
driver.get('http://www.baidu.com')
driver.delete_all_cookies()

for item in cookie_dictionary: 
    driver.add_cookie({
      'domain': '.baidu.com', # note the dot at the beginning
      'name': item['name'],
      'value': item['value'],
      'path': '/',
      'expires': None
    })

driver.get('http://www.baidu.com')
like image 41
HiddenStrawberry Avatar answered Oct 13 '22 21:10

HiddenStrawberry