How to use undetected_chromedriever with a token param?

33 Views Asked by At

Does anyone know how I could pass to the Chrome function of the python undetected_chromedriver (v3.5.5) module a parameter in the header with a token to use in a get request. Thanks in advance

I tried this but it failed me:

def init_webdriver(headless=False, token=None):
    options = uc.ChromeOptions()
    user_agent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 Chrome/122.0.0.0"
    options.add_argument(f"user-agent={user_agent}")
    options.add_argument(f"authorization={token}")
   
    driver = uc.Chrome(headless=headless,options=options)
    return driver
1

There are 1 best solutions below

1
Sujith Rex On

You can use the add_argument method to add the token to the headers of your requests by including it in the Authorization header. However, the add_argument method adds arguments to the Chrome command line, not to the headers of HTTP requests.

To add the token to the headers of your requests, you can use the add_experimental_option method to set the headers option of the ChromeOptions object. Here's an example:

import undetected_chromedriver as uc

def init_webdriver(headless=False, token=None): options = uc.ChromeOptions() user_agent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 Chrome/122.0.0.0" options.add_argument(f"user-agent={user_agent}")

headers = {}
if token:
    headers["Authorization"] = token
    options.add_experimental_option("headers", headers)

driver = uc.Chrome(headless=headless, options=options)
return driver

In this example, the headers dictionary is created outside the if statement so that it can be modified based on the value of the token parameter. If the token parameter is not None, the Authorization header is added to the headers dictionary. Then, the headers dictionary is passed to the add_experimental_option method using the headers key. This sets the headers for all HTTP requests made by the Chrome browser instance.

Note that the undetected_chromedriver module is a wrapper around the selenium module, so the add_experimental_option method is inherited from selenium.webdriver.chrome.options.Options.