How to Use Incognito Mode in Selenium WebDriver
To use
incognito mode in Selenium, create a ChromeOptions object and add the argument --incognito. Then pass this options object when creating the ChromeDriver instance to launch the browser in incognito mode.Syntax
Use ChromeOptions to set browser arguments. Add --incognito to enable incognito mode. Pass the options to ChromeDriver constructor.
- ChromeOptions: Configures Chrome browser settings.
- addArguments("--incognito"): Enables incognito mode.
- ChromeDriver(options): Starts Chrome with given options.
python
from selenium import webdriver from selenium.webdriver.chrome.service import Service from selenium.webdriver.chrome.options import Options options = Options() options.add_argument("--incognito") service = Service() # Use default chromedriver path or specify browser = webdriver.Chrome(service=service, options=options) browser.get("https://www.example.com") browser.quit()
Example
This example shows how to open Chrome in incognito mode, navigate to a website, and then close the browser.
python
from selenium import webdriver from selenium.webdriver.chrome.service import Service from selenium.webdriver.chrome.options import Options options = Options() options.add_argument("--incognito") service = Service() # Assumes chromedriver is in PATH browser = webdriver.Chrome(service=service, options=options) browser.get("https://www.example.com") print("Title of the page:", browser.title) browser.quit()
Output
Title of the page: Example Domain
Common Pitfalls
- Not passing the
optionsobject toChromeDrivercauses the browser to open normally, not in incognito. - Using incorrect argument syntax like
"incognito"instead of"--incognito"will not enable incognito mode. - Forgetting to quit the browser can leave processes running.
python
from selenium import webdriver from selenium.webdriver.chrome.options import Options # Wrong way: missing '--' in argument options_wrong = Options() options_wrong.add_argument("incognito") # Incorrect # Correct way options_right = Options() options_right.add_argument("--incognito") # Wrong: not passing options browser_wrong = webdriver.Chrome() # Right: pass options browser_right = webdriver.Chrome(options=options_right) browser_right.quit()
Quick Reference
Summary tips for using incognito mode in Selenium:
- Always use
--incognitowithadd_argument. - Pass the
Optionsobject to theChromeDriverconstructor. - Ensure
chromedriveris compatible with your Chrome version. - Close the browser with
quit()to free resources.
Key Takeaways
Use ChromeOptions and add the argument '--incognito' to enable incognito mode.
Pass the options object when creating the ChromeDriver instance.
Incorrect argument syntax or missing options causes incognito mode to fail.
Always quit the browser to avoid leftover processes.
Ensure chromedriver matches your Chrome browser version for smooth operation.