在《RobotFramwork + Python 自動化入門 一》中,完成了一個Robot環境搭建及測驗腳本的創建和執行,
在《RobotFramwork + Python 自動化入門 二》中,對RobotFramework的關鍵字使用和查看原始碼進行了介紹,
本節,介紹基于Web的RF自動化,
一、環境配置
1. 下載瀏覽器驅動程式
執行web端的測驗腳本時,需要瀏覽器驅動,不同瀏覽器對應不同的驅動程式,
瀏覽器的驅動版本 要和 瀏覽器版本號對應或適配,
Chrome driver下載地址:http://npm.taobao.org/mirrors/chromedriver/
或百度搜索其他下載方式,
我的Chrome版本號為91.0.4472.106, 故下載最接近的chromedriver,


下載完成后放入Python安裝目錄(或者其他檔案夾,但該檔案夾要加入path路徑),

2.安裝selenium庫
安裝命令(安裝最新版): pip install robotframework-seleniumlibrary
指定版本號安裝:pip install robotframework-seleniumlibrary==3.3.1

3. 添加依賴庫
在RF專案中添加selenium library,
方法一:
雙擊打開red.xml檔案,點擊+按鈕添加library,

選擇Python安裝目錄下的 \Lib\site-packages\SeleniumLibrary 檔案夾中的__init__.py檔案,

選擇第一個SeleniumLibrary,點擊OK,

SeleniumLibrary添加成功,

點擊保存按鈕或 CTRL+S 快捷鍵,
Project目錄下多了一個Robot Referenced libraries目錄,SeleniumLibrary是其子目錄,所有添加的第三方依賴都在這個目錄下,

方法二:
右鍵 red.xml檔案,點擊Open With>Text Editor,以文本格式打開red.xml檔案,

在red.xml檔案中添加下方內容,保存:
<referencedLibrary type="PYTHON" name="SeleniumLibrary" path="D:/Program Files/Python39/Lib/site-packages/SeleniumLibrary"/>

4. 編碼格式設定
在寫中文環境的測驗腳本時,經常會用到中文,故要設定編碼格式為UTF-8,
如果不設定,當腳本中存在中文,執行腳本(robot檔案)會報錯,
而且若只設定了單個專案的編碼格式為UTF-8,在console界面會發現中文字符仍顯示為亂碼,故要設定整個workspace的編碼格式,
設定方法:
選單欄Window > Preferences > General > Workspace,

二、設計測驗腳本
1. 引入SeleniumLibrary
當使用第三方庫時,必須在檔案中使用Library關鍵字 引入相應的庫名,

2. 設計測驗腳本
測驗腳本流程如下:
1.打開谷歌瀏覽器,進入百度頁面
2.搜索框中輸入selenium
3.點擊搜索按鈕
4.頁面搜索結果標題應包含selenium
5.關閉瀏覽器
測驗腳本:
Baidu Search - Selenium
Open Browser http://www.baidu.com chrome # chrome表示啟動谷歌瀏覽器
Wait Until Element Is Visible css=#kw # css=#kw是搜索框的locator,css表示locator使用的是css定位方式
Input Text css=#kw selenium # css=#kw是輸入框的locator
Click Button css=#su
Sleep 3
Element Text Should Be xpath=//h3[@class='t c-gap-bottom-small']/a/em selenium #xpath=//h3[@class='t c-gap-bottom-small']/a/em 是xpath格式的locator
Close Browser

Locator " xpath=//h3[@class='t c-gap-bottom-small']/a/em" 的含義如下:

3. 執行腳本
選擇腳本檔案,右鍵執行,或者直接點擊工具列”執行‘按鈕,

執行結果如下:

轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/288382.html
標籤:其他
下一篇:使用「語雀」搭建個人博客
