環境搭建
selenium 2.53
selenium-java-2.53.0.jar
selenium-java-2.53.0-srcs.jar 原代碼包
拷貝的工程lib下,做build path,告訴項目jar包在lib里
關聯原始代碼:
jar包里都是.class文件,想看原始代碼,關聯源代碼包,在selenium項目包右鍵屬性,選java source attachment,選擇selenium-java-2.53.0-srcs.jar。
package com.thoughtworks.selenium 源代碼
package org.openqa.selenium 開源的代碼
一個driver是一個瀏覽器實例,
selenium2.4.5-javadoc/index.html: api文檔
-org.openqa.selenium.firefox 存放的是Firefox瀏覽器使用的類
- --FirefoxBinary
- --FirefoxDriver 瀏覽器實例
- --FirefoxProfile 用戶配置文件
構造方法重載:不同的方式構造實例
FirefoxDriver()
FirefoxDriver(Capabilities desiredCapabilities)
FirefoxDriver(Capabilities desiredCapabilities, Capabilities requiredCapabilities)
FirefoxDriver(FirefoxBinary binary, FirefoxProfile profile)
FirefoxDriver(FirefoxBinary binary, FirefoxProfile profile, Capabilities capabilities)
FirefoxDriver(FirefoxBinary binary, FirefoxProfile profile, Capabilities desiredCapabilities, Capabilities requiredCapabilities)
FirefoxDriver(FirefoxProfile profile)
package test.selenium; import org.openqa.selenium.WebDriver; import org.openqa.selenium.firefox.FirefoxDriver; public class SeleniumTest { public static void main(String[] args) { // TODO Auto-generated method stub WebDriver driver = new FirefoxDriver(); driver.get("http://nvsm.cnki.net/KNS/"); driver.close(); } }
如果出現打不開瀏覽器,地址欄不能輸入,操作不了頁面dom,都是selenium版本和瀏覽器版本不匹配。selenium更新版本比瀏覽器慢,不能保證支持最新的瀏覽器版本。selenium2.53可以支持Firefox40以下版本。
Webdriver基礎API - 瀏覽器實例管理
- -org.openqa.selenium.ie
- --InternetExplorerDriver
- org.openqa.selenium.chrome
- --ChromeDriver
- public class FirefoxDriver extends RemoteWebDriver
public class RemoteWebDriver extends java.lang.Object implements WebDriver - 如果需要用的Firefox特殊的方法,需強制類型轉換
- appium和selenium用的是一套webdriver協議(多態)
- 執行程序每次打開的都是一個全新的沒有設置的Firefox瀏覽器,設置不會在下次生效。selenium只會在默認路徑(C:\Program Files (x86)\Mozilla Firefox\firefox.exe)找Firefox,如果安裝位置不在默認路徑則會報找不到Firefox可執行文件的錯誤。
- 舉例:讓selenium找的Firefox安裝位置
System.setProperty("webdriver.firefox.bin","C:\\Program Files (x86)\\Mozilla Firefox\\firefox.exe"); WebDriver driver = new FirefoxDriver(); driver.get("http://nvsm.cnki.net/KNS/");
舉例:構造瀏覽器實例
FirefoxDriver(FirefoxBinary binary, FirefoxProfile profile)
FirefoxBinary(java.io.File pathToFirefoxBinary)
FirefoxBinary ffb = new FirefoxBinary(new File("C:\\Program Files (x86)\\Mozilla Firefox\\firefox.exe")); WebDriver driver = new FirefoxDriver(ffb,null); driver.get("http://nvsm.cnki.net/KNS/");
舉例:構造瀏覽器實例(帶配置文件的情況,利用存在的profile文件)
FirefoxProfile(java.io.File profileDir)
FirefoxProfile作用:保存用戶配置信息,包括:瀏覽器設置信息,插件以及設置,書簽和歷史記錄,用戶名和密碼,臨時文件和網站數據,cookies。
cmd命令行輸入:firefox.exe -ProfileManage
C:\Program Files (x86)\Mozilla Firefox>firefox.exe -ProfileManage
運行輸入:%APPDATA%,打開C:\Users\PC\AppData\Roaming,所有的用戶配置信息都在:C:\Users\PC\AppData\Roaming\Mozilla\Firefox\Profiles\1h1iplez.default
FirefoxProfile ffp = new FirefoxProfile(new File("C:\\Users\\PC\\AppData\\Roaming\\Mozilla\\Firefox\\Profiles\\1h1iplez.default")); WebDriver driver = new FirefoxDriver(ffp); driver.get("http://nvsm.cnki.net/KNS/");
舉例:構造瀏覽器實例(帶配置文件的情況,自定義profile文件啟動)
FirefoxProfile有3個重載的方法:
void |
setPreference(java.lang.String key, boolean value)
Set a preference for this particular profile.
|
void |
setPreference(java.lang.String key, int value)
Set a preference for this particular profile.
|
void |
setPreference(java.lang.String key, java.lang.String value)
Set a preference for this particular profile.
|
瀏覽器地址欄輸入:about:config,設置所有的屬性和插件配置
瀏覽器相關配置:browser
例如:設置啟動默認頁面:browser.startup.homepage
FirefoxProfile ffp = new FirefoxProfile(); ffp.setPreference("browser.startup.homepage", "http://nvsm.cnki.net/KNS/"); //設置啟動頁 ffp.setPreference("browser.startup.page", 1); //0空白首頁設置不生效 1用戶自定義首頁 WebDriver driver = new FirefoxDriver(ffp);
Webdriver設置Firefox無提示默認路徑下載
FirefoxProfile ffp = new FirefoxProfile(); ffp.setPreference("browser.download.dir", "C:\\"); ffp.setPreference("browser.download.folderList", 2); // 設置瀏覽器默認下載文件夾 0桌面 1我的下載 2自定義 ffp.setPreference("browser.download.manager.showWhenStarting", false); ffp.setPreference("browser.helperApps.neverAsk.saveToDisk", "application/octet-stream, application/vnd.ms-excel, text/csv, application/zip"); WebDriver driver = new FirefoxDriver(ffp);
firebug插件,網絡查看資源包括靜態資源和js代碼加載快慢,刷新地址可生成網絡布圖,資源加載的時間,參數可以輸出成har文件,可以用showslow打開
舉例:自動收集頁面加載時序圖
FirefoxProfile ffp = new FirefoxProfile(); ffp.addExtension(new File("source\\firebug-2.0.17.xpi")); ffp.addExtension(new File("source\\netExport-0.8.xpi")); // 插件相關 ffp.setPreference("extensions.firebug.allPagesActivation", "on"); //所有頁面自動開啟 ffp.setPreference("extensions.firebug.net.enableSites", "true"); //網絡設置成開啟 ffp.setPreference("extensions.firebug.defaultPanelName","net"); ffp.setPreference("extensions.firebug.netexport.alwaysEnableAutoExport","true"); ffp.setPreference("extensions.firebug.netexport.saveFiles","true"); ffp.setPreference("extensions.firebug.netexport.defaultLogDir", "C:\\"); WebDriver driver = new FirefoxDriver(ffp); Thread.sleep(2000); driver.get("http://nvsm.cnki.net/KNS/");
Driver常用方法(瀏覽器相關操作)
與導航地址欄相關:
get 地址欄輸入地址:driver.get("http://nvsm.cnki.net/kns/brief/result.aspx?dbprefix=CJFQ");
網頁的資源都加載完畢,selenium捕獲網頁狀態,都加載完成方法結束,未加載完會等待默認等待60s,仍未加載完成會向上拋出頁面加載超時的異常。
navigate
back 回退
forward 前進
to 和driver.get()效果差不多,get更成熟
fresh 刷新
getCurrentUrl 盡量不用頁面某個ui元素作為驗證點
getPageSource 獲取網頁的原始代碼
driver.get("http://nvsm.cnki.net/KNS/"); System.out.println(driver.getPageSource()); Pattern p = Pattern.compile("<a.*/a>"); Matcher m = p.matcher(driver.getPageSource()); while(m.find()) { String aa = m.group(); // System.out.println(aa); String[] ss = aa.split("\""); for(String s:ss) { if(s.contains("http://")) { System.out.println(s); driver.get(s); Thread.sleep(5000); } } } }
getTitle 相對用的較少
manage driver.manage() 返回值類型是Options:
driver.manage().addCookie(cookie); driver.manage().window().maximize(); driver.manage().window().fullscreen(); System.out.println(driver.manage().window().getSize().height); System.out.println(driver.manage().window().getSize().width); driver.manage().window().setSize(new Dimension(400,800));
driver.manage().timeouts(); //腳本執行超時限制
quit/close
quit 斷掉http會話
close 關閉當前瀏覽器打開窗口
查詢頁面元素
driver.findElement(By):查詢單個對象,查詢了多個則selenium返回第一個對象
通過id:前端頁面可以沒有頁面元素,有元素就是唯一的id,不會重復
通過Name:Name屬性可以重復
通過className:class屬性的值,class是給頁面一批元素添加一類class屬性
通過LinkText:<a href>和</a>之間的內容
通過PartialLinkText:部分文本值
通過XPATH:
通過CSS選擇器(忽略)
通過TagName:可以用TagName先縮小范圍
組合-連續查找:在findElement找的元素之后,在子元素下繼續查詢元素,縮小范圍
復合元素以及多對象定位:driver.findElements(By)
方法的返回值類型為webElement對象的list(集合形式)
xpath參考:http://www.w3school.com.cn/xpath/index.asp
操作頁面元素
基本控件的調用方法:
輸入框:input -- sendkeys
clear
<input id="user" type="text"> input 標簽 id 屬性
user 屬性值 type 屬性 text 屬性值
FirefoxProfile ffp = new FirefoxProfile(); ffp.setPreference("browser.startup.homepage", "http://nvsm.cnki.net/KNS/"); //設置啟動頁 ffp.setPreference("browser.startup.page", 1); //0空白首頁設置不生效 1用戶自定義首頁 WebDriver driver = new FirefoxDriver(ffp); driver.get("http://nvsm.cnki.net/kns/brief/result.aspx?dbprefix=CJFQ"); driver.findElement(By.id("txt_1_value1")).sendKeys("期刊");
WebDriver driver = new FirefoxDriver(); driver.get("http://nvsm.cnki.net/kns/brief/result.aspx?dbprefix=CJFQ"); WebElement we = driver.findElement(By.id("txt_1_value1")); we.click(); we.clear(); we.sendKeys("期刊");
超鏈接:a -- click
獲取屬性
<a class="baidu" target="_blank" href="https://www.baidu.com/">baidu</a> target="_blank" 每次點都打開新頁簽 selenium稱窗口切換,selenium無法自動切換
可以取href的地址填的地址欄中,操作完再回退至之前的窗口。
WebElement we1 = driver.findElement(By.linkText("新型出版模式介紹")); we1.click(); WebElement we2 = driver.findElement(By.partialLinkText("導航")); we2.click();
WebElement we2 = driver.findElement(By.partialLinkText("導航")); System.out.println(we2.getAttribute("href")); String daohang = we2.getAttribute("href"); driver.get(daohang); Thread.sleep(2000); driver.navigate().back();
下拉菜單:select
WebElement we3 = driver.findElement(By.id("txt_1_sel")); Select select = new Select(we3); List<WebElement> list = select.getOptions(); for(int i = 0;i<list.size();i++) { WebElement we4 = list.get(i); we4.click(); Thread.sleep(3000); } select.selectByVisibleText("全文"); Thread.sleep(2000); select.selectByValue("DOI$=|??"); int num = list.size(); int random = new Random().nextInt(num); select.selectByIndex(num);
單選:radiobox
多選:checkbox -- click
isSelected
List<WebElement> list = driver.findElements(By.xpath("/html/body/form/div[4]/div[2]/div/dl/dd/dl/dd[4]/input")); System.out.println(list.size()); for(int i=2;i<list.size();i++) { list.get(i).click(); Thread.sleep(1000); System.out.println(list.get(i).getAttribute("id"));
System.out.println(list.get(i).isSelected());
}
button -- click
isEnable :判斷頁面的按鈕是否是可點擊的
有可能自動化和手動點擊的操作不同,詢問能否繞過選擇其他方式(回車,提交的接口,觸發鏈接,js,瀏覽器刷新)。
獲取對象屬性或文本值
getAttribute() 取屬性名稱
getText() 取文本值
WebDriver driver = new FirefoxDriver(); driver.get("http://www.huicewang.com/ecshop/"); driver.manage().window().maximize(); //切換精品推薦頁簽 List<WebElement> elements = driver.findElements(By.xpath("//*[@id=\"itemBest\"]/h2/a")); for(WebElement we:elements) { we.click(); Thread.sleep(1000); //取各頁簽中商品價格 List<WebElement> prices = driver.findElements(By.xpath("//*[@id=\"show_best_area\"]/div[@class=\"goodsItem\"]/font")); System.out.println(prices.size()); for(WebElement price:prices) { System.out.println(price.getText()); } //取商品的圖片地址 List<WebElement> photos = driver.findElements(By.xpath("//*[@id=\"show_best_area\"]/div[@class=\"goodsItem\"]/a/img")); for(WebElement photo:photos) { System.out.println(photo.getAttribute("src")); } }
用java.net包發http請求,檢查地址返回值是否是200,保證展示正確。
高級應用
事件操作
Actions類:
位置:org.openqa,selenium.interactions.Actions
作用: