selenium+java實(shí)現(xiàn)web自動(dòng)化例子(附.打開多個(gè)選項(xiàng)卡并可切換操作)

(簡單記錄,有不正確的地方請指出)?selenium+java可以實(shí)現(xiàn)對web頁面的自動(dòng)化控制,在公司內(nèi)部比較穩(wěn)定、頁面迭代較少的后臺(tái)web系統(tǒng)使用時(shí)非常有效

web自動(dòng)化收益最大化的情況

????1.多更新于后端,前端頁面迭代較少

????2.在日常迭代中頁面改動(dòng)小

????3.對新系統(tǒng)最好有一定的復(fù)用性、整合度高

整體說明

web自動(dòng)化相較于app自動(dòng)化比較簡單,只需要導(dǎo)入jar包和瀏覽器驅(qū)動(dòng)

常用的瀏覽器有谷歌和火狐,都有獨(dú)立的驅(qū)動(dòng)程序。驅(qū)動(dòng)放在瀏覽器安裝目錄下

我下載的是chromedriver.exe驅(qū)動(dòng),注意驅(qū)動(dòng)和自己瀏覽器的版本要匹配(我記得最早接觸的時(shí)候還踩過jar包版本和瀏覽器版本不兼容的坑,已經(jīng)很久了,具體情況已經(jīng)忘記,可以注意下)


驅(qū)動(dòng)存放截圖
項(xiàng)目結(jié)構(gòu)


整個(gè)代碼以及注釋

public void getLogin_Tieba(){

System.out.print("開始web自動(dòng)化!!");

System.setProperty("webdriver.chrome.driver", "C:\\Program Files (x86)\\Google\\Chrome\\Application\\chromedriver.exe");

? ? ? ? WebDriver driver = new ChromeDriver();

driver.get("https://www.baidu.com/");

? ? ? ? WebElement searchBox=driver.findElement(By.linkText("貼吧"));

? ? ? ? searchBox.click();

? ? ? ? try {

Thread.sleep(5000);

} catch (InterruptedException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

? ? ? ? WebElement searchBox1=driver.findElement(By.linkText("登錄"));

? ? ? ? searchBox1.click();

? ? ? ? try {

Thread.sleep(5000);

} catch (InterruptedException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

? ? ? ? WebElement searchP=driver.findElement(By.id("TANGRAM__PSP_10__footerULoginBtn"));

? ? ? ? searchP.click();

? ? ? ? WebElement searchBox2=driver.findElement(By.id("TANGRAM__PSP_10__userName"));

? ? ? ? searchBox2.sendKeys("18228013236");

? ? ? ? WebElement searchBox3=driver.findElement(By.id("TANGRAM__PSP_10__password"));

? ? ? ? searchBox3.sendKeys("abcdefg123");

? ? ? ? WebElement searchBox4=driver.findElement(By.id("TANGRAM__PSP_10__submit"));

? ? ? ? searchBox4.click();

try {

Thread.sleep(10000);

} catch (InterruptedException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

driver.quit();

}


代碼截圖

代碼內(nèi)容解釋

控件的操作,在appium+java實(shí)際例子中有詳細(xì)說明,這里就不累述

添加驅(qū)動(dòng):System.setProperty("webdriver.chrome.driver", "C:\\Program Files (x86)\\Google\\Chrome\\Application\\chromedriver.exe");

創(chuàng)建驅(qū)動(dòng)對象:WebDriver driver = new ChromeDriver();如果是火狐則需要調(diào)整WebDriver driver = new FirefoxDriver();

打開指定地址:driver.get("https://www.baidu.com/");

根據(jù)控件Test屬性值獲取控件,并創(chuàng)建對象:WebElement searchBox=driver.findElement(By.linkText("貼吧"));

執(zhí)行單擊事件:searchBox.click();


打開多個(gè)選項(xiàng)卡并可切換不同選項(xiàng)卡進(jìn)行操作

第一步、先定義好需要用到的url

第二步、創(chuàng)建Robot對象,模擬按鍵操作,達(dá)到打開新選項(xiàng)卡的目的

第三步、獲得所有選項(xiàng)卡的句柄,再定位進(jìn)行操作

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容