How can I use Selenium to interact with a website's cookies?

Selenium WebDriver allows you to interact with cookies in a website for testing purposes. You can add, delete, and retrieve cookies using Selenium's built-in methods.

Here's how you can do it in Python and JavaScript:

Python

You can use the add_cookie() method to add cookies. Here's an example of adding a cookie:

from selenium import webdriver

driver = webdriver.Firefox()
driver.get("http://www.example.com")

# Add a cookie
cookie = {'name' : 'foo', 'value' : 'bar'}
driver.add_cookie(cookie)

To retrieve all cookies, you can use the get_cookies() method:

# Get all cookies
cookies = driver.get_cookies()
print(cookies)

To retrieve a specific cookie by name, you can use the get_cookie() method:

# Get a specific cookie
cookie = driver.get_cookie('foo')
print(cookie)

To delete a specific cookie, you can use the delete_cookie() method:

# Delete a specific cookie
driver.delete_cookie('foo')

To delete all cookies, you can use the delete_all_cookies() method:

# Delete all cookies
driver.delete_all_cookies()

JavaScript

In WebDriverJS, the methods are similar:

To add a cookie:

var webdriver = require('selenium-webdriver');

var driver = new webdriver.Builder()
    .forBrowser('firefox')
    .build();

driver.get('http://www.example.com');

// Add a cookie
driver.manage().addCookie({name: 'foo', value: 'bar'});

To retrieve all cookies:

// Get all cookies
driver.manage().getCookies().then(function(cookies) {
    console.log(cookies);
});

To retrieve a specific cookie by name:

// Get a specific cookie
driver.manage().getCookie('foo').then(function(cookie) {
    console.log(cookie);
});

To delete a specific cookie:

// Delete a specific cookie
driver.manage().deleteCookie('foo');

To delete all cookies:

// Delete all cookies
driver.manage().deleteAllCookies();

Remember that these operations should be performed when you're on the domain that the cookie will be set on, and after the page load. If you navigate away from the page or close the browser, the cookies will be lost.

Get Started Now

WebScraping.AI provides rotating proxies, Chromium rendering and built-in HTML parser for web scraping
Icon