Python學(xué)習(xí)筆記:Day8-使用selenium控制手chrome瀏覽器
使用Selenium控制Chrome瀏覽器
# -*- coding: UTF-8 -*-
__author__ = 'Fengwangbeichui'
import os
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
chromedriver = "D:\Portableapps\PortableApps\GoogleChromePortable\App\Chrome-bin\chromedriver.exe"
os.environ["webdriver.chrome.driver"] = chromedriver
driver = webdriver.Chrome(chromedriver)
url = 'http://pluscmstest.miaohealth.net/login.html'
driver.get(url)
diver.close()
driver.quit()
利用selenium控制手動打開的chrome瀏覽器
我們可以利用Chrome DevTools協(xié)議。它允許客戶檢查和調(diào)試Chrome瀏覽器。
打開cmd,在命令行中輸入命令:
chrome.exe --remote-debugging-port=9222 --user-data-dir="C:\selenum\AutomationProfile"
- 對于-remote-debugging-port值,可以指定任何打開的端口。
- 對于-user-data-dir標(biāo)記,指定創(chuàng)建新Chrome配置文件的目錄。它是為了確保在單獨的配置文件中啟動chrome,不會污染你的默認配置文件。
- 還有,不要忘了在環(huán)境變量中PATH里將chrome的路徑添加進去。
此時會打開一個瀏覽器頁面,我們輸入百度網(wǎng)址,我們把它當(dāng)成一個已存在的瀏覽器。
現(xiàn)在,我們需要接管上面的瀏覽器。新建一個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)
會發(fā)現(xiàn)打印出了 “百度一下,你就知道” 的網(wǎng)頁標(biāo)題。這樣我們就實現(xiàn)了對一個已打開的瀏覽器的控制。