如何查看python selenium的API
python -m pydoc -p 4567
說明:
python -m pydoc表示打開pydoc模塊,pydoc是查看python文檔的首選工具;
-p 4567表示在4567端口上啟動server
然后在瀏覽器中訪問http://localhost:4567/,此時應該可以看到python中所有的Modules按ctrl+f,輸入selenium,定位到selenium文檔的鏈接,然后點擊進入到http://localhost:4567/selenium.html這個頁面
這就是selenium文檔所在的位置了,接下來便可以根據自己的需要進行查看了。舉個例子,如果你想查看Webdriver類的基本方法,可以訪問這個頁面http://localhost:4567/selenium.webdriver.remote.webdriver.html
Firefox瀏覽器調用
Firefox瀏覽器驅動添加
Firefox原生支持,無需下載驅動,只要安裝瀏覽器即可
Firefox瀏覽器的調用
#coding=utf-8 from selenium import webdriver driver=webdriver.Firefox() url='http://www.baidu.com' driver.get(url) driver.close()
說明:
1、【#coding=utf-8】為了防止亂碼問題,以便在程序中添加中文注釋,把編碼統一為UTF-8,注意=兩遍不要留空格,否則不起作用,另外【#_*_coding:utf-8_*_】的寫法也可以達到相同的作用
2、【from selenium import webdriver】該步驟是導入selenium的webdriver包,只有導入selenium包,我們才能使用webdriver API進行自動化腳本的開發
3、【driver=webdriver.Firefox()】這里將控制webdriver的Firefox賦值給driver,通過driver獲得瀏覽器操作對象,后就可以啟動瀏覽器、打開網址、操作對應的頁面元素了。
Firefox自動運行中需要啟動固定插件
首先,根據上述的瀏覽器調用,webdriver在啟動瀏覽器時,啟動的一個干凈的沒有任務、插件及cookies信息的瀏覽器(即使你本機的firefox安裝了某些插件,webdriver啟動firefox也是沒有這些插件的),但是有可能被測系統本身需要插件或者需要調試等等,此時腳本會卡主無法運行,那么該如何解決呢?在解答問題前,先了解下,如何自定義帶有特定配置的Firefox。
自定義Firefox配置文件
步驟如下:
1.運行CMD,打開Firefox的 Profile manager
2.點擊"Create Profile...",完成步驟,包括輸入Profile名字
3.點擊"Start Firefox"
4.在新啟動的Firefox中安裝自己所需要的Add-On或者做其他配置
附:java代碼:
string sPath = @"C:\Users\xxxx\AppData\Roaming\Mozilla\Firefox\Profiles\5f3xae4a.default"; FirefoxProfile ffprofile = new FirefoxProfile(sPath);
方法一:使用自定義的Firefox profile
用webdriver驅動firefox瀏覽器時如果不設置參數,默認使用的Firefox的profile和平時打開瀏覽器使用的firefox不一樣,如果要使用平常使用的配置,需要增加如下操作:
profile_dir="C:\Users\admin\AppData\Roaming\Mozilla\Firefox\Profiles\wrdjxgdk.default-1434681389856" profile = webdriver.FirefoxProfile(profile_dir) driver = webdriver.Firefox(profile)
增加上述配置后,再調用driver進行get操作即可,其中黃色背景部分為Firefox的prifiles文件目錄,一般都在:C:\Users\admin\AppData\Roaming\Mozilla\Firefox\Profiles目錄下,至於啟動什么樣的瀏覽器,可以根據自己的需要定義,如:
a. 瀏覽網站,必須安裝的插件,都安裝完畢,且設置為:總是激活
b. 必要的安全設置等
方法二:使用代碼進行配置
該方法是直接在代碼里面進行插件的安裝和profile的配置,如下先舉例firebug插件的調用:
profile=webdriver.FirefoxProfile() #加載插件 profile.add_extension('c:\\firebug-2.0.8-fx.xpi') #激活插件
profile.set_preference("extensions.firebug.allPagesActivation", "on") driver=webdriver.Firefox(profile)
增加上述配置后,再調用driver進行get操作即可。
我們除了可以使用上面提到的方法定制插件,webdriver還可以對profile進行定制(在firefox地址欄中輸入about:config,可以查看firefox的參數),下面舉例設置代理和默認下載路徑:
myweb="192.168.9.111" myport="8080" profile=webdriver.FirefoxProfile() #設置代理 profile.set_preference("network.proxy.type", 1) profile.set_preference("network.proxy.http", myweb) profile.set_preference("network.proxy.http_port", myport) #設置文件下載目錄 profile.set_preference("browser.download.folderList", 2) profile.set_preference("browser.download.dir", "C:\\test") driver=webdriver.Firefox(profile)
增加上述配置后,再調用driver進行get操作即可
參考資料
[1]Selenium2(WebDriver)總結(一)---啟動瀏覽器、設置profile&加載插件,
http://www.cnblogs.com/puresoul/p/4251536.html
[2]Webdriver使用自定義Firefox Profile運行測試,
http://lijingshou.iteye.com/blog/2085276
[3]記錄我遇到的selenium哪些令人摸不着頭腦的問題,