在使用selenium進行自動化測試中我們有時會遇到這樣的情況:
我們需要手動打開瀏覽器,進入到所需的頁面,執行一些手動任務,如輸入表單、輸入驗證碼,登陸成功后,然后再開始運行自動化腳本。
這種情況下如何使用selenium來接管先前已打開的瀏覽器呢?
這里給出Google Chrome瀏覽器的解決方案。
我們可以利用Chrome DevTools協議。它允許客戶檢查和調試Chrome瀏覽器。
打開cmd,在命令行中輸入命令:
chrome.exe --remote-debugging-port=9222 --user-data-dir="C:\selenum\AutomationProfile"
對於-remote-debugging-port值,可以指定任何打開的端口。
對於-user-data-dir標記,指定創建新Chrome配置文件的目錄。它是為了確保在單獨的配置文件中啟動chrome,不會污染你的默認配置文件。
還有,不要忘了在環境變量中PATH里將chrome的路徑添加進去。
此時會打開一個瀏覽器頁面,我們輸入百度網址,我們把它當成一個已存在的瀏覽器。
現在,我們需要接管上面的瀏覽器。新建一個python文件,運行以下代碼:
from selenium import webdriver from selenium.webdriver.chrome.options import Options chrome_options = Options() chrome_options.add_experimental_option("debuggerAddress", "127.0.0.1:9222") chrome_driver = "chromedriver.exe" driver = webdriver.Chrome(chrome_driver, chrome_options=chrome_options) print(driver.title) driver.get("https://intoli.com/blog/not-possible-to-block-chrome-headless/chrome-headless-test.html")
會發現打印出了 “百度一下,你就知道” 的網頁標題。這樣我們就實現了對一個已打開的瀏覽器的控制。
更多需求可以自己在此基礎上進行修改。
轉自http://www.teachmeselenium.com/2018/08/11/how-to-connect-selenium-to-an-existing-browser-that-was-opened-manually/
翻譯http://www.cnblogs.com/lovealways
補充:由於測試上面代碼時,我還沒安裝chromedriver,於是用以下代碼安裝:
pip install chromedriver
又從這里找到http://chromedriver.storage.googleapis.com/index.html chromedriver.exe(win32版本的) 放在當前腳本目錄中(后來發現其實也不用下載,可以用之前C#代碼測試時的chromedriver.exe)
然而,上面的代碼證明,沒能通過WebDriver反爬檢測。
最終參考https://www.cnblogs.com/bgmc/p/12154484.html bgmc的文章,將代碼改成:
from selenium import webdriver from selenium.webdriver.chrome.options import Options chrome_options = Options() chrome_options.add_experimental_option("debuggerAddress", "127.0.0.1:9222") chrome_driver = "chromedriver.exe" driver = webdriver.Chrome(chrome_driver, chrome_options=chrome_options) script = ''' Object.defineProperty(navigator, 'webdriver', { get: () => undefined }) ''' driver.execute_cdp_cmd("Page.addScriptToEvaluateOnNewDocument", {"source": script}) print(driver.title) driver.get("https://intoli.com/blog/not-possible-to-block-chrome-headless/chrome-headless-test.html")
哈哈,通過檢測!
參考:https://www.cnblogs.com/lovealways/p/9813059.html
https://www.cnblogs.com/bgmc/p/12154484.html