使用python+selenium控制手工已打開的瀏覽器

咱們能夠利用Chrome DevTools協議。它容許客戶檢查和調試Chrome瀏覽器。html

打開cmd,在命令行中輸入命令:python

chrome.exe --remote-debugging-port=9222 --user-data-dir="C:\selenum\AutomationProfile"

      對於-remote-debugging-port值,能夠指定任何打開的端口。web

      對於-user-data-dir標記,指定建立新Chrome配置文件的目錄。它是爲了確保在單獨的配置文件中啓動chrome,不會污染你的默認配置文件。chrome

      還有,不要忘了在環境變量中PATH裏將chrome的路徑添加進去。瀏覽器

此時會打開一個瀏覽器頁面,咱們輸入百度網址,咱們把它當成一個已存在的瀏覽器:spa

如今,咱們須要接管上面的瀏覽器。新建一個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 = "C:\Program Files (x86)\Google\Chrome\Application\chromedriver.exe"
driver = webdriver.Chrome(chrome_driver, chrome_options=chrome_options)
print(driver.title)
複製代碼

會發現打印出了 「百度一下,你就知道」 的網頁標題。這樣咱們就實現了對一個已打開的瀏覽器的控制。翻譯

更多需求能夠本身在此基礎上進行修改。debug

ps:調試

driver.maximize_window()這個方法貌似不能用,報錯:operation is unsupported with remote debugging:遠程調試不支持操做

轉自http://www.cnblogs.com/lovealways/p/9813059.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

相關文章
相關標籤/搜索