通過 Google 的Chrome Devtools-Protocol(Chrome 開發工具協議)簡稱CDP,給定一段 JavaScript 代碼,讓 Chrome 剛剛打開頁面,還沒有運行網站自帶的 JavaScript代碼時,執行給定的代碼。
使用driver.execute_cdp_cmd:根據 Selenium 的官方文檔,傳入需要調用的 CDP 命令和參數即可
import time from selenium import webdriver from selenium.webdriver import ActionChains url = "https://www.qcc.com/user_login?back=%2F" option = webdriver.ChromeOptions() PROXY = "proxy_host:proxy:port" desired_capabilities = option.to_capabilities() desired_capabilities['proxy'] = { "httpProxy": PROXY, "ftpProxy": PROXY, "sslProxy": PROXY, "noProxy": None, "proxyType": "MANUAL", "class": "org.openqa.selenium.Proxy", "autodetect": False } option.add_experimental_option('excludeSwitches', ['enable-automation']) # webdriver防檢測 option.add_experimental_option('useAutomationExtension', False) driver = webdriver.Chrome(options=option,desired_capabilities=desired_capabilities) # CDP執行JavaScript 代碼 重定義windows.navigator.webdriver的值 driver.execute_cdp_cmd("Page.addScriptToEvaluateOnNewDocument", { "source": """ Object.defineProperty(navigator, 'webdriver', { get: () => undefined }) """ }) driver.get(url) time.sleep(2) driver.find_element_by_id('normalLogin').click() # 點擊密碼登入 time.sleep(1) #輸入賬號密碼 driver.find_element_by_id('nameNormal').send_keys('1341632010') driver.find_element_by_id('pwdNormal').send_keys('HEIYUN_320') #獲取滑塊 button = driver.find_element_by_id('nc_1_n1z') # 滑動滑塊 ActionChains(driver).click_and_hold(button).perform() ActionChains(driver).move_by_offset(xoffset=308, yoffset=0).perform() ActionChains(driver).release().perform() driver.find_element_by_xpath('//*[@id="user_login_normal"]/button').click() time.sleep(1) driver.quit()
完美隱藏window.navigator.webdriver。並且,關鍵語句只需要執行一次,之后只要你不關閉這個driver開啟的窗口,無論你打開多少個網址,他都會自動提前在網站自帶的所有 js 之前執行這個語句,隱藏window.navigator.webdriver。
