1. 程式人生 > >Selenium WebDriver的簡單操作說明

Selenium WebDriver的簡單操作說明

1.開啟一個測試瀏覽器

對瀏覽器進行操作首先需要開啟一個瀏覽器,接下來才能對瀏覽器進行操作。

Java程式碼

import org.openqa.selenium.WebDriver;

importorg.openqa.selenium.firefox.FirefoxBinary;

importorg.openqa.selenium.firefox.FirefoxDriver;

importorg.openqa.selenium.ie.InternetExplorerDriver;

public class OpenBrowsers {

         public static void main(String[] args) {

                   //開啟預設路徑的firefox

                   WebDriver diver = new FirefoxDriver();

                   //開啟指定路徑的firefox,方法1

                   System.setProperty("webdriver.firefox.bin","D:\\ProgramFiles\\MozillaFirefox\\firefox.exe");

                   WebDriver dr = new FirefoxDriver();

                   //開啟指定路徑的firefox,方法2

                   File pathToFirefoxBinary = newFile("D:\\Program Files\\Mozilla Firefox\\firefox.exe"); 

                   FirefoxBinary firefoxbin = newFirefoxBinary(pathToFirefoxBinary); 

                   WebDriver driver1 = newFirefoxDriver(firefoxbin,null);

                   //開啟ie

                   WebDriver ie_driver = new InternetExplorerDriver();

                   //開啟chrome

                   System.setProperty("webdriver.chrome.driver","D:\\chromedriver.exe");

                   System.setProperty("webdriver.chrome.bin",

                                            "C:\\Documents and Settings\\gongjf\\Local Settings"

                                             +"\\ApplicationData\\Google\\Chrome\\Application\\chrome.exe");

         }

}

2.開啟1個具體的url

開啟一個瀏覽器後,我們需要跳轉到特定的url下,看下面程式碼:

Java程式碼

import org.openqa.selenium.WebDriver;

importorg.openqa.selenium.firefox.FirefoxDriver;

public class OpenUrl {

         publicstatic void main(String []args){

                   Stringurl = "http://www.51.com";

                   WebDriverdriver = new FirefoxDriver();

                   //用get方法

                   driver.get(url);

                   //用navigate方法,然後再呼叫to方法

                   driver.navigate().to(url);

         }

}

3.如何關閉瀏覽器

測試完成後,需要關閉瀏覽器

Java程式碼

import org.openqa.selenium.WebDriver;

importorg.openqa.selenium.firefox.FirefoxDriver;

public class CloseBrowser {

         publicstatic void main(String []args){

                   Stringurl = "http://www.51.com";

                   WebDriverdriver = new FirefoxDriver();

                   driver.get(url);

                   //用quit方法

                   driver.quit();

                   //用close方法       

                   driver.close();

                   }

}

4.如何返回當前頁面的url和title

有時候我們需要返回當前頁面的url或者title做一些驗證性的操作等。程式碼如下:

Java程式碼

import org.openqa.selenium.WebDriver;

importorg.openqa.selenium.firefox.FirefoxDriver;

public class GetUrlAndTitle {

         publicstatic void main(String []args){

                   Stringurl = "http://www.google.com";

                   WebDriverdriver = new FirefoxDriver();

                   driver.get(url);

                //得到title

                   Stringtitle = driver.getTitle();

                //得到當前頁面url

                   StringcurrentUrl = driver.getCurrentUrl();

                //輸出title和currenturl

                   System.out.println(title+"\n"+currentUrl);

                   }

}

5.其他方法

getWindowHandle()    返回當前的瀏覽器的視窗控制代碼

getWindowHandles()  返回當前的瀏覽器的所有視窗控制代碼

getPageSource()        返回當前頁面的原始碼

從上面程式碼可以看出操作瀏覽器的主要方法都來自org.openqa.selenium.WebDriver這個介面中。看了一下原始碼這些方法都是在org.openqa.selenium.remote.RemoteWebDriver這個類中實現的,然後不同瀏覽的driver類繼承RemoteWebDriver。

C  定位頁面元素

selenium-webdriver提供了強大的元素定位方法,支援以下三種方法。

單個物件的定位方法

多個物件的定位方法

層級定位 

定位單個元素

在定位單個元素時,selenium-webdriver提示瞭如下一些方法對元素進行定位。

 By.className(className))    

 By.cssSelector(selector)       

 By.id(id)                     

 By.linkText(linkText)          

 By.name(name)             

 By.partialLinkText(linkText)

 By.tagName(name)       

 By.xpath(xpathExpression)  

注意:selenium-webdriver通過findElement()\findElements()等find方法呼叫"By"物件來定位 和查詢元素。By類只是提供查詢的方式進行分類。findElement返回一個元素物件否則丟擲異常,findElements返回符合條件的元素 List,如果不存在符合條件的就返回一個空的list。

1.使用className進行定位

當所定位的元素具有class屬性的時候我們可以通過classname來定位該元素。

下面的例子定位了51.com首頁上class為"username"的li。

Java程式碼

import org.openqa.selenium.WebDriver;

import org.openqa.selenium.WebElement;

import org.openqa.selenium.By;

public class ByClassName {

   public static void main(String[] args) {

        WebDriver driver = new FirefoxDriver();

       driver.get("http://www.51.com");

        WebElement element =driver.findElement(By.className("username"));

        System.out.println(element.getTagName());

    }

}

輸出結果:

Java程式碼

Li

2.使用id屬性定位

51.com首頁的帳號輸入框的html程式碼如下:

Java程式碼

<input id="passport_51_user"type="text" value="" tabindex="1" title="使用者名稱/彩虹號/郵箱"

name="passport_51_user">

在下面的例子中用id定位這個輸入框,並輸出其title,藉此也可以驗證程式碼是否工作正常。

Java程式碼

import org.openqa.selenium.By;

import org.openqa.selenium.WebDriver;

import org.openqa.selenium.WebElement;

importorg.openqa.selenium.firefox.FirefoxDriver;

public class ByUserId {

         /**

          * @param args

          */

         publicstatic void main(String[] args) {

                   //TODO Auto-generated method stub

                   WebDriverdr = new FirefoxDriver();

                   dr.get("http://www.51.com");

                   WebElementelement = dr.findElement(By.id("passport_51_user"));

                   System.out.println(element.getAttribute("title"));

         }

}

輸出結果:

 Java程式碼

使用者名稱/彩虹號/郵箱

3.使用name屬性定位

51.com首頁的帳號輸入框的html程式碼如下:

Java程式碼

<input id="passport_51_user"type="text" value="" tabindex="1" title="使用者名稱/彩虹號/郵箱"

name="passport_51_user">

使用name定位

Java程式碼

import org.openqa.selenium.By;

import org.openqa.selenium.WebDriver;

import org.openqa.selenium.WebElement;

importorg.openqa.selenium.firefox.FirefoxDriver;

public class ByUserId {

         /**

          * @param args

          */

         publicstatic void main(String[] args) {

                   //TODO Auto-generated method stub

                   WebDriverdr = new FirefoxDriver();

                   dr.get("http://www.51.com");

         WebElemente = dr.findElement(By.name("passport_51_user"));                                      System.out.println(element.getAttribute("title"));

         }

}

輸出結果:

 Java程式碼

使用者名稱/彩虹號/郵箱

4.使用css屬性定位

51.com首頁的帳號輸入框的html程式碼如下:

Java程式碼

<input id="passport_51_user"type="text" value="" tabindex="1" title="使用者名稱/彩虹號/郵箱"

name="passport_51_user">

使用css定位

Java程式碼

WebElement e1 =dr.findElement(By.cssSelector("#passport_51_user"));

5.使用 XPATH定位

51.com首頁的帳號輸入框的html程式碼如下:

Java程式碼

<input id="passport_51_user"type="text" value="" tabindex="1" title="使用者名稱/彩虹號/郵箱"

name="passport_51_user">

通過xpath查詢:

Java程式碼

WebElement element=driver.findElement(By.xpath("//input[@id=' passport_51_user ']"));

6.使用其他方式定位

在定位link元素的時候,可以使用link和link_text屬性;

另外還可以使用tag_name屬性定位任意元素;

7.定位多個元素

上面提到findElements()方法可以返回一個符合條件的元素List組。看下面例子。

Java程式碼

import java.io.File;

import java.util.List;

import org.openqa.selenium.By;

import org.openqa.selenium.WebDriver;

import org.openqa.selenium.WebElement;

importorg.openqa.selenium.firefox.FirefoxBinary;

import org.openqa.selenium.firefox.FirefoxDriver;

public class FindElementsStudy {

         /**

          * @author gongjf

          */

         publicstatic void main(String[] args) {

                   WebDriver  driver = new FirefoxDriver();

                   driver.get("http://www.51.com");

                   //定位到所有<input>標籤的元素,然後輸出他們的id

                   List<WebElement>element = driver.findElements(By.tagName("input"));

                   for(WebElement e : element){

                            System.out.println(e.getAttribute("id"));

                   }

                   driver.quit();

         }

}

輸出結果:

Java程式碼

passport_cookie_login

gourl

passport_login_from

passport_51_user

passport_51_password

passport_qq_login_2

btn_reg

passport_51_ishidden

passport_auto_login

上面的程式碼返回頁面上所有input物件

8.層級定位

層級定位的思想是先定位父元素,然後再從父元素中精確定位出其我們需要選取的子元素。

層級定位一般的應用場景是無法直接定位到需要選取的元素,但是其父元素比較容易定位,通過定位父元素再遍歷其子元素選擇需要的目標元素,或者需要定位某個元素下所有的子元素。

下面的程式碼演示瞭如何使用層級定位class為"login"的div,然後再取得它下面的所有label,並打印出他們的文字

Java程式碼

importjava.util.List;

importorg.openqa.selenium.By;

importorg.openqa.selenium.WebDriver;

importorg.openqa.selenium.WebElement;

importorg.openqa.selenium.firefox.FirefoxBinary;

importorg.openqa.selenium.firefox.FirefoxDriver;

publicclass LayerLocator {

         /**

          * @author gongjf

          */

         public static void main(String[] args){

                   WebDriver  driver = new FirefoxDriver();

                   driver.get("http://www.51.com");

                   //定位class為"login"的div,然後再取得它下面的所有label,並打印出他們的值

                   WebElement element =driver.findElement(By.className("login"));

                    List<WebElement> el =element.findElements(By.tagName("label"));

                    for(WebElement e : el)

                   System.out.println(e.getText());

         }       

}

輸出結果:

Java程式碼

帳號:

密碼:

隱身

 D  如何對頁面元素進行操作

找到頁面元素後,怎樣對頁面進行操作呢?我們可以根據不同的型別的元素來進行一一說明。

1. 輸入框(text field or textarea)

 找到輸入框元素:

WebElement element =driver.findElement(By.id("passwd-id"));

在輸入框中輸入內容:

element.sendKeys(“test”);

將輸入框清空:

element.clear();

獲取輸入框的文字內容:

element.getText();

2. 下拉選擇框(Select)

找到下拉選擇框的元素:

Select select = newSelect(driver.findElement(By.id("select")));

選擇對應的選擇項:

select.selectByVisibleText(“mediaAgencyA”);

select.selectByValue(“MA_ID_001”);

不選擇對應的選擇項:

select.deselectAll();

select.deselectByValue(“MA_ID_001”);

select.deselectByVisibleText(“mediaAgencyA”);

或者獲取選擇項的值:

select.getAllSelectedOptions();

select.getFirstSelectedOption();

對下拉框進行操作時首先要定位到這個下拉框,new 一個Selcet物件,然後對它進行操作 

3. 單選項(Radio Button)

找到單選框元素:

WebElement bookMode =driver.findElement(By.id("BookMode"));

選擇某個單選項:

bookMode.click();

清空某個單選項:

bookMode.clear();

判斷某個單選項是否已經被選擇:

bookMode.isSelected();

4. 多選項(checkbox)

多選項的操作和單選的差不多:

WebElement checkbox=driver.findElement(By.id("myCheckbox."));

checkbox.click();

checkbox.clear();

checkbox.isSelected();

checkbox.isEnabled();

5. 按鈕(button)

找到按鈕元素:

WebElement saveButton =driver.findElement(By.id("save"));

點選按鈕:

saveButton.click();

判斷按鈕是否enable:

saveButton.isEnabled ();

6. 左右選擇框

也就是左邊是可供選擇項,選擇後移動到右邊的框中,反之亦然。例如:

Select lang = new Select(driver.findElement(By.id("languages")));

lang.selectByVisibleText(“English”);

WebElement addLanguage=driver.findElement(By.id("addButton"));

addLanguage.click();

7. 彈出對話方塊(Popup dialogs)

Alert alert = driver.switchTo().alert();

alert.accept();

alert.dismiss();

alert.getText();

後面有具體的例子解釋~

8. 表單(Form)

Form中的元素的操作和其它的元素操作一樣,對元素操作完成後對錶單的提交可以:

WebElement approve =driver.findElement(By.id("approve"));

approve.click();

approve.submit();//只適合於表單的提交

9. 上傳檔案 (Upload File)

上傳檔案的元素操作:

WebElement adFileUpload = driver.findElement(By.id("WAP-upload"));

String filePath ="C:\test\\uploadfile\\media_ads\\test.jpg";

adFileUpload.sendKeys(filePath);

10.拖拉(Drag andDrop)

WebElement element=driver.findElement(By.name("source"));

WebElement target = driver.findElement(By.name("target"));

(new Actions(driver)).dragAndDrop(element,target).perform();

11.導航 (Navigationand History)

開啟一個新的頁面:

 driver.navigate().to("http://www.example.com");

通過歷史導航返回原頁面:

driver.navigate().forward();

driver.navigate().back();

E  iframe的處理

有時候我們在定位一個頁面元素的時候發現一直定位不了,反覆檢查自己寫的定位器沒有任何問題,程式碼也沒有任何問題。這時你就要看一下這個頁面元素是否在一個iframe中,這可能就是找不到的原因之一。如果你在一個default content中查詢一個在iframe中的元素,那肯定是找不到的。反之你在一個iframe中查詢另一個iframe元素或default content中的元素,那必然也定位不到。

selenium webdriver中提供了進入一個iframe的方法:

WebDriverorg.openqa.selenium.WebDriver.TargetLocator.frame(String nameOrId)

也提供了一個返回default content的方法:

WebDriver org.openqa.selenium.WebDriver.TargetLocator.defaultContent()

這樣使我們面對iframe時可以輕鬆應對。

以下面的html程式碼為例,我們看一下處現iframe。

Html程式碼

main.html

<html>

   <head>

       <title>FrameTest</title>

相關推薦

python selenium-webdriver 元素操作之鍵盤操作

height decimal page 常用 trac max keys span web selenium 提供了比較完整的鍵盤操作,在使用的模擬鍵盤操作之前需要我們導入from selenium.webdriver.common.keys import Keys即可,然

Selenium+Webdriver部分操作(一)

- 清除文字 driver.find_element_by_id("kw").clear() # 呼叫clear()方法去清除 - 重新整理當前頁面 driver.refresh() - 瀏覽器前進和後退操作 driver.back() # 從百

(轉)python selenium-webdriver 元素操作之滑鼠和鍵盤事件

參考資料:https://blog.csdn.net/zh175578809/article/details/76767748 參考資料2:https://blog.csdn.net/qq_41817302/article/details/79618654   selenium 提供了比較完整的鍵盤操作,

Selenium WebDriver基礎操作教程

最近幾個月在研究Selenium WebDriver,簡單總結一下我的入坑記。 一、在Java 環境中的安裝 1.選取合適的瀏覽器   在配置Selenium的WebDriver前首先先選定測試的瀏覽器,IE、Chrome、Firefox等主流瀏覽

Selenium WebDriver簡單操作說明

1.開啟一個測試瀏覽器 對瀏覽器進行操作首先需要開啟一個瀏覽器,接下來才能對瀏覽器進行操作。 Java程式碼 import org.openqa.selenium.WebDriver; importorg.openqa.sele

web自動化8-selenium簡單操作方法

bdr url isp nbt web selenium attr () 尺寸 1. 控制窗口大小 form selenium import webdriver driver = webdriver.Chrome() driver.get("http://www.ba

selenium+python自動化測試(二)對瀏覽器的簡單操作

cat quit 報錯 簡單 conn port ted href ide 1.最大化 maximize_window 1 # coding = utf-8 2 3 from selenium import webdriver 4 chromedriver =

webdriver firefox瀏覽器簡單操作

forward www. web driver ive 火狐 ref res max 打開火狐瀏覽器:driver = webdriver.Firefox() 打開百度:driver.get(‘http://www.baidu.com‘)設置窗口大小400*800: dri

selenium webdriver學習--通過id、name定位,輸入內容,搜索,關閉操作

prop void exc tps ogl ati class 輸入 hbox selenium webdriver學習--通過id、name定位,輸入內容,搜索,關閉操作; 打開谷歌瀏覽器,輸入不同的網站,搜索框的定位含有不同元素(有時為id,有時為name) imp

(java)selenium webdriver學習---實現簡單的翻頁,將頁面內容的標題和標題鏈接取出

prop imp current inter 並且 常見問題 activity num div selenium webdriver學習---實現簡單的翻頁,將頁面內容的標題和標題鏈接取出; 該情況適合能能循環page=1~n,並且每個網頁隨著循環可以打開的情況, 註意一定

Python3 Selenium WebDriver網頁的前進、後退、重新整理、最大化、獲取視窗位置、設定視窗大小、獲取頁面title、獲取網頁原始碼、獲取Url等基本操作

Python3 Selenium WebDriver網頁的前進、後退、重新整理、最大化、獲取視窗位置、設定視窗大小、獲取頁面title、獲取網頁原始碼、獲取Url等基本操作 通過selenium webdriver操作網頁前進、後退、重新整理、最大化、獲取視窗位置、設定視窗大小、獲取頁面title、獲取網頁

【python】用selenium webdriver簡單的表格提交

selenium webdriver是一個自動化測試工具,相比於直接用get之類的方法能更為直觀的模擬使用者使用,但是,對我而言就是,額,挺好玩的,所以這一篇的側重點是一個接觸的過程,並沒有很系統的闡述這個工具。 註明:以下都以Chrome為例,IE可能在某些部分細節有所

Selenium Webdriver之Chrome瀏覽器操作小記

Selenium Selenium 是一套跨平臺的瀏覽器自動化測試框架(工具),支援在多種系統環境、多種瀏覽器環境下使用,還可以使用多種程式語言來編寫測試。 Selenium 有多個專案構成,形成了一個多功能的測試系統: Selenium Core:支援DHTML 的

selenium webdriver 模擬滑鼠鍵盤的操作

selenium通過命令進行驅動,其中一種風格就是action(動作)。actions命令一般用於操作應用程式的狀態,通過“點選”和“選擇”的方式進行工作。webdriver繼承了selenium中的actions類,這個actions類中,主要是模擬使用者的滑鼠mouse

Selenium-WebDriver API命令與操作——八種元素定位

原文地址:http://www.seleniumhq.org/docs/03_webdriver.jsp#selenium-webdriver-api-commands-and-operations (本文只針對python部分翻譯) 首先申明一點:本人英語水平很爛,做此翻

Selenium webdriver操作日曆控制元件

一般的日期控制元件都是input標籤下彈出來的,如果使用webdriver 去設定日期,   1. 定位到該input   2. 使用sendKeys 方法   比如:   但是,有的日期控制元件是readonly的   比如12306的這個   <input id

MySQL基本概念以及簡單操作

software 倉庫 必須 key 不能 即使 同時 databases ecif 一、MySQL   MySQL是一個關系型數據庫管理系統,由瑞典MySQL AB 公司開發,目前屬於Oracle 旗下產品。MySQL 是最流行的關系型數據庫管理系統之一,在 WEB

數據庫簡單操作

更新 模式 eat from use col 區分 tab 容器 第一章 了解MySQL 數據庫 保存有組織的數據的容器。(通常是一個文件或一組文件) 人們經常使用數據庫這個術語代替他們使用的軟件。這是不正確的,確切的說,數據庫軟件應稱為DB

總結Selenium WebDriver中一些鼠標和鍵盤事件的使用

ict 效果 control window 只需要 html 執行 text keyevent 在使用 Selenium WebDriver 做自動化測試的時候,會經常模擬鼠標和鍵盤的一些行為。比如使用鼠標單擊、雙擊、右擊、拖拽等動作;或者鍵盤輸入、快捷鍵使用、組合鍵使用

Python-模塊:OS,目錄及文件的簡單操作

-1 close pytho print nbsp nco 刪除目錄 os.path window 1.目錄操作 #encoding=UTF-8import unittest,osfrom time import sleep print dir(os)#獲取文件路徑‘‘‘獲