有谁知道如何将标头中的参数传递给 python unDetected_chromedriver (v3.5.5) 模块的 Chrome 函数,并在 get 请求中使用令牌。 预先感谢
我尝试过,但失败了:
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
您可以使用 add_argument 方法将令牌添加到请求的标头中,方法是将其包含在授权标头中。但是,add_argument 方法将参数添加到 Chrome 命令行,而不是 HTTP 请求的标头。
要将令牌添加到请求的标头中,您可以使用 add_experimental_option 方法来设置 ChromeOptions 对象的 headers 选项。这是一个例子:
import undetected_chromedriver as uc
def init_webdriver(无头=假,令牌=无): 选项 = 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
在此示例中,标头字典是在 if 语句外部创建的,以便可以根据 token 参数的值进行修改。如果 token 参数不是 None,则 Authorization 标头将添加到标头字典中。然后,使用 headers 键将 headers 字典传递给 add_experimental_option 方法。这将为 Chrome 浏览器实例发出的所有 HTTP 请求设置标头。
请注意,unDetected_chromedriver 模块是 selenium 模块的包装器,因此 add_experimental_option 方法继承自 selenium.webdriver.chrome.options.Options。