1. 安裝
1.1. 安裝
Selenium Python bindings 提供了一個簡單的API,讓你使用Selenium WebDriver來編寫功能/校驗測試。 通過Selenium Python的API,你可以非常直觀的使用Selenium WebDriver的所有功能。
Selenium Python bindings 使用非常簡潔方便的API讓你去使用像Firefox, IE, Chrome, Remote等等 這樣的Selenium WebDrivers(Selenium web驅動器)。當前支持的版本為 2.7, 3.2及以上。
本文的用來講解說明Selenium 2 WebDriver的API,此文檔不包含Selenium 1 / Selenium RC的文檔。
1.2. 下載 Python bindings for Selenium
可以從PyPI的官方庫中下載該selenium支持庫,?點此下載?當然, 更好的方法當然是使用?pip?命令來安裝selenium包。 Python3.5的?`標準庫 <Installing Python Modules — Python 3.5.10 documentation>`_中包含pip命令。 使用?`pip`命令,你可以像下面這樣安裝 selenium:
pip install selenium
Note
使用Python2.x版本的用戶可以手動安裝pip或者easy_install,下面是easy_install 的安裝方法:
easy_install selenium
你可以考慮使用`virtualenv <http://www.virtualenv.org>`_ 創建獨立的Python環境。Python3.5中`pyvenv <5. Additional Tools and Scripts — Python 3.5.10 documentation>`_ 可以提供幾乎一樣的功能。
1.3. Windows用戶的詳細說明
Note
請在有網的情況下執行該安裝命令。
-
安裝Python3.5:官方下載頁.
-
從開始菜單點擊運行(或者`Windows+R`)輸入`cmd`,然后執行下列命令安裝:
C:\Python35\Scripts\pip.exe install selenium
現在你可以使用Python運行測試腳本了。 例如:如果你創建了一個selenium的基本示例并且保存在了``C:my_selenium_script.py``,你可以如下執行:
C:\Python35\python.exe C:\my_selenium_script.py
1.4. 下載 Selenium 服務器
Note
如果你想使用一個遠程的WebDriver,Selenium服務是唯一的依賴, 參見?使用遠程 Selenium WebDriver?獲得更多細節。 如果你只是剛剛開始學習使用Selenium,你可以忽略該章節直接開始下一節。
Selenium server是一個JAVA工程,Java Runtime Environment (JRE) 1.6或者更高的版本是推薦的運行環境。
你可以在?該下載頁?下載2.x的Selenium server,這個文件大概長成這個樣子:selenium-server-standalone-2.x.x.jar
, 你可以去下載最新版本的2.x server。
如果你還沒有安裝Java Runtime Environment (JRE)的話, 呢,在這下載, 如果你是有的是GNU/Linux系統,并且巧了,你還有root權限,你還可以使用操作系統指令去安裝JRE。
如果你把`java`命令放在了PATH(環境變量)中的話,使用下面命令安裝:
java -jar selenium-server-standalone-2.x.x.jar
當然了,把``2.x.x``換成你下載的實際版本就可以了。
如果是不是root用戶你或者沒有把JAVA放到PATH中, 你可以使用絕對路徑或者相對路徑的方式來使用命令, 這個命令大概長這樣子:
/path/to/java -jar /path/to/selenium-server-standalone-2.x.x.jar
2. 快速入門
2.1. 簡單用例
如果你已經安裝好了selenium,你可以把下面的python代碼拷貝到你的編輯器中
from selenium import webdriver from selenium.webdriver.common.keys import Keysdriver = webdriver.Firefox() driver.get("http://www.python.org") assert "Python" in driver.title elem = driver.find_element_by_name("q") elem.clear() elem.send_keys("pycon") elem.send_keys(Keys.RETURN) assert "No results found." not in driver.page_source driver.close()
上面的腳本可以保存到一個文件(如:-?python_org_search.py),那么可以這樣使用
python python_org_search.py
你運行的?python?環境中應該已經安裝了?selenium?模塊。
2.2. 示例詳解
selenium.webdriver?模塊提供了所有WebDriver的實現, 當前支持的WebDriver有: Firefox, Chrome, IE and Remote。?`Keys`類提供鍵盤按鍵的支持,比如:RETURN, F1, ALT等
from selenium import webdriver from selenium.webdriver.common.keys import Keys
接下來,創建一個Firefox WebDriver的實例
driver = webdriver.Firefox()
driver.get?方法將打開URL中填寫的地址,WebDriver 將等待, 直到頁面完全加載完畢(其實是等到”onload” 方法執行完畢),然后返回繼續執行你的腳本。 值得注意的是,如果你的頁面使用了大量的Ajax加載, WebDriver可能不知道什么時候頁面已經完全加載:
driver.get("http://www.python.org")
下一行是用assert的方式確認標題是否包含“Python”一詞。 (譯注:assert 語句將會在之后的語句返回false后拋出異常,詳細內容可以自行百度)
assert "Python" in driver.title
WebDriver 提供了大量的方法讓你去查詢頁面中的元素,這些方法形如:?find_element_by_*。 例如:包含?name?屬性的input輸入框可以通過?find_element_by_name?方法查找到, 詳細的查找方法可以在第四節元素查找中查看:
elem = driver.find_element_by_name("q")
接下來,我們發送了一個關鍵字,這個方法的作用類似于你用鍵盤輸入關鍵字。 特殊的按鍵可以使用Keys類來輸入,該類繼承自?selenium.webdriver.common.keys, 為了安全起見,我們先清除input輸入框中的任何預填充的文本(例如:”Search”),從而避免我們的搜索結果受影響:
elem.clear() elem.send_keys("pycon") elem.send_keys(Keys.RETURN)
提交頁面后,你會得到所有的結果。為了確保某些特定的結果被找到,使用`assert`如下:
assert "No results found." not in driver.page_source
最后,關閉瀏覽器窗口,你還可以使用quit方法代替close方法, quit將關閉整個瀏覽器,而_close——只會關閉一個標簽頁, 如果你只打開了一個標簽頁,大多數瀏覽器的默認行為是關閉瀏覽器:
driver.close()
2.3. 用Selenium寫測試用例
Selenium 通常被用來寫一些測試用例.?selenium?包本身不提供測試工具或者框架. 你可以使用Python自帶的模塊unittest寫測試用例。 The other options for a tool/framework are py.test and nose.
在本章中,我們使用?unittest?來編寫測試代碼,下面是一個已經寫好的用例。 這是一個在?python.org?站點上搜索的案例:
import unittest from selenium import webdriver from selenium.webdriver.common.keys import Keysclass PythonOrgSearch(unittest.TestCase):def setUp(self):self.driver = webdriver.Firefox()def test_search_in_python_org(self):driver = self.driverdriver.get("http://www.python.org")self.assertIn("Python", driver.title)elem = driver.find_element_by_name("q")elem.send_keys("pycon")elem.send_keys(Keys.RETURN)assert "No results found." not in driver.page_sourcedef tearDown(self):self.driver.close()if __name__ == "__main__":unittest.main()
你可以在shell中運行下列代碼:
python test_python_org_search.py . ---------------------------------------------------------------------- Ran 1 test in 15.566sOK
結果表明這個測試用例已經成功運行。
2.4. 逐步解釋測試代碼
一開始,我們引入了需要的模塊,?unittest?模塊是基于JAVA JUnit的Python內置的模塊。 該模塊提供了一個框架去組織測試用例。?selenium.webdriver?模塊提供了所有WebDriver的實現。 現在支持的WebDriver有:Firefox, Chrome, IE and Remote.?Keys?類提供所有的鍵盤按鍵操作,比如像這樣的:
RETURN, F1, ALT等。
import unittest from selenium import webdriver from selenium.webdriver.common.keys import Keys
該測試類繼承自?unittest.TestCase. 繼承?TestCase?類是告訴?unittest?模塊該類是一個測試用例:
class PythonOrgSearch(unittest.TestCase):
setUp?方法是初始化的一部分, 該方法會在該測試類中的每一個測試方法被執行前都執行一遍。 下面創建了一個Firefox WebDriver的一個實例。
def setUp(self):self.driver = webdriver.Firefox()
這是一個測試用例實際的測試方法. 測試方法始終以?test`開頭。 在該方法中的第一行創建了一個在 `setUp?方法中創建的驅動程序對象的本地引用。
def test_search_in_python_org(self):driver = self.driver
driver.get?方法將會根據方法中給出的URL地址打開該網站。 WebDriver 會等待整個頁面加載完成(其實是等待”onload”事件執行完畢)之后把控制權交給測試程序。 如果你的頁面使用大量的AJAX技術來加載頁面,WebDriver可能不知道什么時候頁面已經加載完成:
driver.get("http://www.python.org")
下面一行使用assert斷言的方法判斷在頁面標題中是否包含 “Python”
self.assertIn("Python", driver.title)
WebDriver 提供很多方法去查找頁面值的元素,這些方法都以?find_element_by_*?開頭。 例如:包含?name?屬性的input元素可以使用
find_element_by_name`方法查找到。詳細的細節可以參照 :ref:`locating-elements?章節:
elem = driver.find_element_by_name("q")
接下來我們發送keys,這個和使用鍵盤輸入keys類似。 特殊的按鍵可以通過引入`selenium.webdriver.common.keys`的?Keys?類來輸入
elem.send_keys("pycon") elem.send_keys(Keys.RETURN)
提交頁面之后,無論如何你都會得到搜索結果,為了確保某些結果類檢索到,可以使用下列斷言 After submission of the page, you should get result as per search if
assert "No results found." not in driver.page_source
tearDown?方法會在每一個測試方法執行之后被執行。 該方法可以用來做一些清掃工作,比如關閉瀏覽器。 當然你也可以調用?quit?方法代替`close`方法,
quit?將關閉整個瀏覽器,而`close`只會關閉一個標簽頁, 如果你只打開了一個標簽頁,大多數瀏覽器的默認行為是關閉瀏覽器。
def tearDown(self):self.driver.close()
下面是入口函數:
if __name__ == "__main__":unittest.main()
2.5. 使用遠程 Selenium WebDriver
為了使用遠程 WebDriver, 你應該擁有一個正在運行的 Selenium 服務器。 通過下列命令運行服務器:
java -jar selenium-server-standalone-2.x.x.jar
Selenium 服務運行后, 你會看到這樣的提示信息:
15:43:07.541 INFO - RemoteWebDriver instances should connect to: http://127.0.0.1:4444/wd/hub
上面一行告訴你,你可以通過這個URL連接到遠程WebDriver, 下面是一些例子:
from selenium import webdriver from selenium.webdriver.common.desired_capabilities import DesiredCapabilitiesdriver = webdriver.Remote(command_executor='http://127.0.0.1:4444/wd/hub',desired_capabilities=DesiredCapabilities.CHROME)driver = webdriver.Remote(command_executor='http://127.0.0.1:4444/wd/hub',desired_capabilities=DesiredCapabilities.OPERA)driver = webdriver.Remote(command_executor='http://127.0.0.1:4444/wd/hub',desired_capabilities=DesiredCapabilities.HTMLUNITWITHJS)
`desired_capabilities`是一個字典,如果你不想使用默認的字典,你可以明確指定的值
driver = webdriver.Remote(command_executor='http://127.0.0.1:4444/wd/hub',desired_capabilities={'browserName': 'htmlunit','version': '2','javascriptEnabled': True})
3. 打開一個頁面
你想做的第一件事也許是使用WebDriver打開一個鏈接。 常規的方法是調用?get
?方法:
driver.get("http://www.google.com")
WebDriver 將等待,直到頁面完全加載完畢(其實是等到?onload
?方法執行完畢), 然后返回繼續執行你的腳本。 值得注意的是,如果你的頁面使用了大量的Ajax加載, WebDriver可能不知道什么時候頁面已經完全加載。 如果你想確保也main完全加載完畢,可以使用:ref:waits <waits>
3.1. 與頁面交互
只是打開頁面其實并沒有什么卵用。我們真正想要的是與頁面做交互。 更具體地說,對于一個頁面中的HTML元素,首先我們要找到他。WebDriver 提供了大量的方法幫助你去查找元素,例如:已知一個元素定義如下:
<input type="text" name="passwd" id="passwd-id" />
你可以通過下面的方法查找他:
element = driver.find_element_by_id("passwd-id") element = driver.find_element_by_name("passwd") element = driver.find_element_by_xpath("//input[@id='passwd-id']")
你還可以通過鏈接的文本查找他,需要注意的是,這個文本必須完全匹地配。 當你使用`XPATH`時,你必須注意,如果匹配超過一個元素,只返回第一個元素。 如果上面也沒找到,將會拋出?``NoSuchElementException``異常。
WebDriver有一個”基于對象”的API; 我們使用相同的接口表示所有類型的元素。 這就意味著,當你打開你的IDE的自動補全的時候,你會有很多可以調用的方法。 但是并不是所有的方法都是有意義或是有效的。不過不要擔心! 當你調用一些毫無意義的方法時,WebDriver會嘗試去做一些正確的事情(例如你對一個”meta” 元素調用”setSelected()”方法的時候)。
所以,當你拿到ige元素時,你能做什么呢?首先,你可能會想在文本框中輸入一些內容:
element.send_keys("some text")
你還可以通過”Keys”類來模式輸入方向鍵:
element.send_keys(" and some", Keys.ARROW_DOWN)
對于任何元素,他可能都叫?send_keys?,這就使得它可以測試鍵盤快捷鍵, 比如當你使用Gmail的時候。但是有一個副作用是當你輸入一些文本時,這些 輸入框中原有的文本不會被自動清除掉,相反,你的輸入會繼續添加到已存在文本之后。 你可以很方便的使用?clear?方法去清除input或者textarea元素中的內容:
element.clear()
3.2. 填寫表格
我們已經知道如何在input或textarea元素中輸入內容,但是其他元素怎么辦? 你可以“切換”下拉框的狀態,你可以使用``setSelected``方法去做一些事情,比如 選擇下拉列表,處理`SELECT`元素其實沒有那么麻煩:
element = driver.find_element_by_xpath("//select[@name='name']") all_options = element.find_elements_by_tag_name("option") for option in all_options:print("Value is: %s" % option.get_attribute("value"))option.click()
上面這段代碼將會尋找頁面第一個 “SELECT” 元素, 并且循環他的每一個OPTION元素, 打印從utamen的值,然后按順序都選中一遍。
正如你說看到的那樣,這不是處理 SELECT 元素最好的方法。WebDriver的支持類包括一個叫做?``Select``的類,他提供有用的方法處理這些內容:
from selenium.webdriver.support.ui import Select select = Select(driver.find_element_by_name('name')) select.select_by_index(index) select.select_by_visible_text("text") select.select_by_value(value)
WebDriver 也提供一些有用的方法來取消選擇已經選擇的元素:
select = Select(driver.find_element_by_id('id')) select.deselect_all()
這將取消選擇所以的OPTION。
假設在一個案例中,我們需要列出所有已經選擇的選項,Select類提供了方便的方法來實現這一點:
select = Select(driver.find_element_by_xpath("xpath")) all_selected_options = select.all_selected_options
獲得所以選項:
options = select.options
一旦你填寫完整個表單,你應該想去提交它,有一個方法就是去找到一個“submit” 按鈕然后點擊它:
# Assume the button has the ID "submit" :) driver.find_element_by_id("submit").click()
或者,WebDriver對每一個元素都有一個叫做 “submit” 的方法,如果你在一個表單內的 元素上使用該方法,WebDriver會在DOM樹上就近找到最近的表單,返回提交它。 如果調用的元素不再表單內,將會拋出``NoSuchElementException``異常:
element.submit()
3.3. 拖放
您可以使用拖放,無論是移動一個元素,或放到另一個元素內:
element = driver.find_element_by_name("source") target = driver.find_element_by_name("target")from selenium.webdriver import ActionChains action_chains = ActionChains(driver) action_chains.drag_and_drop(element, target).perform()
3.4. 在不同的窗口和框架之間移動
對于現在的web應用來說,沒有任何frames或者只包含一個window窗口是比較罕見的。 WebDriver 支持在不同的窗口之間移動,只需要調用``switch_to_window``方法即可:
driver.switch_to_window("windowName")
所有的?driver
?將會指向當前窗口,但是你怎么知道當前窗口的名字呢,查看打開他的javascript或者連接代碼:
<a href="somewhere.html" target="windowName">Click here to open a new window</a>
或者,你可以在”switch_to_window()”中使用”窗口句柄”來打開它, 知道了這些,你就可以迭代所有已經打開的窗口了:
for handle in driver.window_handles:driver.switch_to_window(handle)
你還可以在不同的frame中切換 (or into iframes):
driver.switch_to_frame("frameName")
通過“.”操作符你還可以獲得子frame,并通過下標指定任意frame,就像這樣:
driver.switch_to_frame("frameName.0.child")
如何獲取名叫“frameName”的frame中名叫 “child”的子frame呢??來自*top*frame的所有的frame都會被評估?(All frames are evaluated as if from *top*.)
一旦我們完成了frame中的工作,我們可以這樣返回父frame:
driver.switch_to_default_content()
3.5. 彈出對話框
Selenium WebDriver 內置了對處理彈出對話框的支持。 在你的某些動作之后可能會觸發彈出對話框,你可以像下面這樣訪問對話框:
alert = driver.switch_to_alert()
它將返回當前打開的對話框對象。使用此對象,您現在可以接受、排除、讀取其內容, 甚至可以在prompt對話框中輸入(譯注:prompt()是對話框的一種,不同于alert()對話框,不同點可以自行百度)。 這個接口對alert, confirm, prompt 對話框效果相同。 參考相關的API文檔獲取更多信息。
3.6. 訪問瀏覽器歷史記錄
在之前的文章中,我們使用``get``命令打開一個頁面, (?driver.get("http://www.example.com")
),WebDriver有很多更小的,以任務為導向的接口, navigation就是一個有用的任務,打開一個頁面你可以使用`get`:
driver.get("http://www.example.com")
在瀏覽歷史中前進和后退你可以使用:
driver.forward() driver.back()
請注意,這個功能完全取決于底層驅動程序。當你調用這些方法的時候,很有可能會發生意想不到的事情, 如果你習慣了瀏覽器的這些行為于其他的不同。(原文:It’s just possible that something unexpected may happen when you call these methods if you’re used to the behaviour of one browser over another.)
3.7. 操作Cookies
在我們結束這一節之前,或許你對如何操作Cookies可能會很感興趣。 首先,你需要打開一個也面,因為Cookie是在某個域名下才生效的:
::
# 打開一個頁面 driver.get(“http://www.example.com”)
# 現在設置Cookies,這個cookie在域名根目錄下(”/”)生效 cookie = {‘name’ : ‘foo’, ‘value’ : ‘bar’} driver.add_cookie(cookie)
# 現在獲取所有當前URL下可獲得的Cookies driver.get_cookies()
?
4. 查找元素
在一個頁面中有很多不同的策略可以定位一個元素。在你的項目中, 你可以選擇最合適的方法去查找元素。Selenium提供了下列的方法給你:
- find_element_by_id
- find_element_by_name
- find_element_by_xpath
- find_element_by_link_text
- find_element_by_partial_link_text
- find_element_by_tag_name
- find_element_by_class_name
- find_element_by_css_selector
一次查找多個元素 (這些方法會返回一個list列表):
- find_elements_by_name
- find_elements_by_xpath
- find_elements_by_link_text
- find_elements_by_partial_link_text
- find_elements_by_tag_name
- find_elements_by_class_name
- find_elements_by_css_selector
除了上述的公共方法,下面還有兩個私有方法,在你查找也頁面元素的時候也許有用。 他們是?find_element?和?find_elements?。
用法示例:
from selenium.webdriver.common.by import Bydriver.find_element(By.XPATH, '//button[text()="Some text"]') driver.find_elements(By.XPATH, '//button')
下面是?By?類的一些可用屬性:
ID = "id" XPATH = "xpath" LINK_TEXT = "link text" PARTIAL_LINK_TEXT = "partial link text" NAME = "name" TAG_NAME = "tag name" CLASS_NAME = "class name" CSS_SELECTOR = "css selector"
4.1. 通過ID查找元素
當你知道一個元素的?id?時,你可以使用本方法。在該策略下,頁面中第一個該?id?元素 會被匹配并返回。如果找不到任何元素,會拋出?NoSuchElementException
?異常。
作為示例,頁面元素如下所示:
<html><body><form id="loginForm"><input name="username" type="text" /><input name="password" type="password" /><input name="continue" type="submit" value="Login" /></form></body> <html>
可以這樣查找表單(form)元素:
login_form = driver.find_element_by_id('loginForm')
4.2. 通過Name查找元素
當你知道一個元素的?name?時,你可以使用本方法。在該策略下,頁面中第一個該?name?元素 會被匹配并返回。如果找不到任何元素,會拋出?NoSuchElementException
?異常。
作為示例,頁面元素如下所示:
<html><body><form id="loginForm"><input name="username" type="text" /><input name="password" type="password" /><input name="continue" type="submit" value="Login" /><input name="continue" type="button" value="Clear" /></form> </body> <html>
name屬性為 username & password 的元素可以像下面這樣查找:
username = driver.find_element_by_name('username') password = driver.find_element_by_name('password')
這會得到 “Login” 按鈕,因為他在 “Clear” 按鈕之前:
continue = driver.find_element_by_name('continue')
4.3. 通過XPath查找元素
XPath是XML文檔中查找結點的語法。因為HTML文檔也可以被轉換成XML(XHTML)文檔, Selenium的用戶可以利用這種強大的語言在web應用中查找元素。 XPath擴展了(當然也支持)這種通過id或name屬性獲取元素的簡單方式,同時也開辟了各種新的可能性, 例如獲取頁面上的第三個復選框。
使用XPath的主要原因之一就是當你想獲取一個既沒有id屬性也沒有name屬性的元素時, 你可以通過XPath使用元素的絕對位置來獲取他(這是不推薦的),或相對于有一個id或name屬性的元素 (理論上的父元素)的來獲取你想要的元素。XPath定位器也可以通過非id和name屬性查找元素。
絕對的XPath是所有元素都從根元素的位置(HTML)開始定位,只要應用中有輕微的調整,會就導致你的定位失敗。 但是通過就近的包含id或者name屬性的元素出發定位你的元素,這樣相對關系就很靠譜, 因為這種位置關系很少改變,所以可以使你的測試更加強大。
作為示例,頁面元素如下所示:
<html><body><form id="loginForm"><input name="username" type="text" /><input name="password" type="password" /><input name="continue" type="submit" value="Login" /><input name="continue" type="button" value="Clear" /></form> </body> <html>
可以這樣查找表單(form)元素:
login_form = driver.find_element_by_xpath("/html/body/form[1]") login_form = driver.find_element_by_xpath("//form[1]") login_form = driver.find_element_by_xpath("//form[@id='loginForm']")
- 絕對定位 (頁面結構輕微調整就會被破壞)
- HTML頁面中的第一個form元素
- 包含?id?屬性并且其值為?loginForm?的form元素
username元素可以如下獲取:
username = driver.find_element_by_xpath("//form[input/@name='username']") username = driver.find_element_by_xpath("//form[@id='loginForm']/input[1]") username = driver.find_element_by_xpath("//input[@name='username']")
- 第一個form元素中包含name屬性并且其值為?username?的input元素
- id為?loginForm?的form元素的第一個input子元素
- 第一個name屬性為?username?的input元素
“Clear” 按鈕可以如下獲取:
clear_button = driver.find_element_by_xpath("//input[@name='continue'][@type='button']") clear_button = driver.find_element_by_xpath("//form[@id='loginForm']/input[4]")
- Input with attribute named?name?and the value?continue?and attribute named?type?and the value?button
- Fourth input child element of the form element with attribute named?id?and value?loginForm
這些實例都是一些舉出用法, 為了學習更多有用的東西,下面這些參考資料推薦給你:
- W3Schools XPath Tutorial
- W3C XPath Recommendation
- XPath Tutorial?- with interactive examples.
還有一些非常有用的插件,可以協助發現元素的XPath:
- XPath Checker?- suggests XPath and can be used to test XPath results.
- Firebug?- XPath suggestions are just one of the many powerful features of this very useful add-on.
- XPath Helper?- for Google Chrome
4.4. 通過鏈接文本獲取超鏈接
當你知道在一個錨標簽中使用的鏈接文本時使用這個。 在該策略下,頁面中第一個匹配鏈接內容錨標簽 會被匹配并返回。如果找不到任何元素,會拋出?NoSuchElementException
?異常。
作為示例,頁面元素如下所示:
<html><body><p>Are you sure you want to do this?</p><a href="continue.html">Continue</a><a href="cancel.html">Cancel</a> </body> <html>
continue.html 超鏈接可以被這樣查找到:
continue_link = driver.find_element_by_link_text('Continue') continue_link = driver.find_element_by_partial_link_text('Conti')
4.5. 通過標簽名查找元素
當你向通過標簽名查找元素時使用這個。 在該策略下,頁面中第一個匹配該標簽名的元素 會被匹配并返回。如果找不到任何元素,會拋出?NoSuchElementException
?異常。
作為示例,頁面元素如下所示:
<html><body><h1>Welcome</h1><p>Site content goes here.</p> </body> <html>
h1 元素可以如下查找:
heading1 = driver.find_element_by_tag_name('h1')
4.6. 通過Class name 定位元素
當你向通過class name查找元素時使用這個。 在該策略下,頁面中第一個匹配該class屬性的元素 會被匹配并返回。如果找不到任何元素,會拋出?NoSuchElementException
?異常。
作為示例,頁面元素如下所示:
<html><body><p class="content">Site content goes here.</p> </body> <html>
p 元素可以如下查找:
content = driver.find_element_by_class_name('content')
4.7. 通過CSS選擇器查找元素
當你向通過CSS選擇器查找元素時使用這個。 在該策略下,頁面中第一個匹配該CSS 選擇器的元素 會被匹配并返回。如果找不到任何元素,會拋出?NoSuchElementException
?異常。
作為示例,頁面元素如下所示:
<html><body><p class="content">Site content goes here.</p> </body> <html>
p 元素可以如下查找:
content = driver.find_element_by_css_selector('p.content')
5. 等待頁面加載完成(Waits)
現在的大多數的Web應用程序是使用Ajax技術。當一個頁面被加載到瀏覽器時, 該頁面內的元素可以在不同的時間點被加載。這使得定位元素變得困難, 如果元素不再頁面之中,會拋出?ElementNotVisibleException?異常。 使用 waits, 我們可以解決這個問題。waits提供了一些操作之間的時間間隔- 主要是定位元素或針對該元素的任何其他操作。
Selenium Webdriver 提供兩種類型的waits - 隱式和顯式。 顯式等待會讓WebDriver等待滿足一定的條件以后再進一步的執行。 而隱式等待讓Webdriver等待一定的時間后再才是查找某元素。
5.1. 顯式等待
顯式等待是你在代碼中定義等待一定條件發生后再進一步執行你的代碼。 最糟糕的案例是使用time.sleep(),它將條件設置為等待一個確切的時間段。 這里有一些方便的方法讓你只等待需要的時間。WebDriverWait結合ExpectedCondition 是實現的一種方式。
from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as ECdriver = webdriver.Firefox() driver.get("http://somedomain/url_that_delays_loading") try:element = WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.ID, "myDynamicElement"))) finally:driver.quit()
在拋出TimeoutException異常之前將等待10秒或者在10秒內發現了查找的元素。 WebDriverWait 默認情況下會每500毫秒調用一次ExpectedCondition直到結果成功返回。 ExpectedCondition成功的返回結果是一個布爾類型的true或是不為null的返回值。
預期的條件
自動化的Web瀏覽器中一些常用的預期條件,下面列出的是每一個實現, Selenium Python binding都提供了一些方便的方法,這樣你就不用去編寫 expected_condition類或是創建至今的工具包去實現他們。 - title_is - title_contains - presence_of_element_located - visibility_of_element_located - visibility_of - presence_of_all_elements_located - text_to_be_present_in_element - text_to_be_present_in_element_value - frame_to_be_available_and_switch_to_it - invisibility_of_element_located - element_to_be_clickable - 顯示并可用. - staleness_of - element_to_be_selected - element_located_to_be_selected - element_selection_state_to_be - element_located_selection_state_to_be - alert_is_present
from selenium.webdriver.support import expected_conditions as ECwait = WebDriverWait(driver, 10) element = wait.until(EC.element_to_be_clickable((By.ID,'someid')))
expected_conditions 模塊提供了一組預定義的條件供WebDriverWait使用。
5.2. 隱式等待
如果某些元素不是立即可用的,隱式等待是告訴WebDriver去等待一定的時間后去查找元素。 默認等待時間是0秒,一旦設置該值,隱式等待是設置該WebDriver的實例的生命周期。
from selenium import webdriverdriver = webdriver.Firefox() driver.implicitly_wait(10) # seconds driver.get("http://somedomain/url_that_delays_loading") myDynamicElement = driver.find_element_by_id("myDynamicElement")
6. 頁面對象
本章是一個針對頁面對象設計模式的教程引導。 一個頁面對象表示在你測試的WEB應用程序的用戶界面上的區域。
使用頁面對象模式的好處:
- 創建可復用的代碼以便于在多個測試用例間共享
- 減少重復的代碼量
- 如果用戶界面變化,只需要修改一處
6.1. 測試用例
下面是一個在python.org網站搜索一個詞并保證一些結果可以找到的測試用例。
import unittest from selenium import webdriver import pageclass PythonOrgSearch(unittest.TestCase):"""A sample test class to show how page object works"""def setUp(self):self.driver = webdriver.Firefox()self.driver.get("http://www.python.org")def test_search_in_python_org(self):"""Tests python.org search feature. Searches for the word "pycon" then verified that some results show up.Note that it does not look for any particular text in search results page. This test verifies thatthe results were not empty."""#Load the main page. In this case the home page of Python.org.main_page = page.MainPage(self.driver)#Checks if the word "Python" is in titleassert main_page.is_title_matches(), "python.org title doesn't match."#Sets the text of search textbox to "pycon"main_page.search_text_element = "pycon"main_page.click_go_button()search_results_page = page.SearchResultsPage(self.driver)#Verifies that the results page is not emptyassert search_results_page.is_results_found(), "No results found."def tearDown(self):self.driver.close()if __name__ == "__main__":unittest.main()
6.2. 頁面對象類
頁面對象為每個網頁模擬創建出一個對象。 按照此技術,在測試代碼和技術實施之間的一個分離層被創建。
這個?page.py
?看起來像這樣:
from element import BasePageElement from locators import MainPageLocatorsclass SearchTextElement(BasePageElement):"""This class gets the search text from the specified locator"""#The locator for search box where search string is enteredlocator = 'q'class BasePage(object):"""Base class to initialize the base page that will be called from all pages"""def __init__(self, driver):self.driver = driverclass MainPage(BasePage):"""Home page action methods come here. I.e. Python.org"""#Declares a variable that will contain the retrieved textsearch_text_element = SearchTextElement()def is_title_matches(self):"""Verifies that the hardcoded text "Python" appears in page title"""return "Python" in self.driver.titledef click_go_button(self):"""Triggers the search"""element = self.driver.find_element(*MainPageLocators.GO_BUTTON)element.click()class SearchResultsPage(BasePage):"""Search results page action methods come here"""def is_results_found(self):# Probably should search for this text in the specific page# element, but as for now it works finereturn "No results found." not in self.driver.page_source
6.3. 頁面元素
這個?element.py
?看起來像這樣:
from selenium.webdriver.support.ui import WebDriverWaitclass BasePageElement(object):"""Base page class that is initialized on every page object class."""def __set__(self, obj, value):"""Sets the text to the value supplied"""driver = obj.driverWebDriverWait(driver, 100).until(lambda driver: driver.find_element_by_name(self.locator))driver.find_element_by_name(self.locator).send_keys(value)def __get__(self, obj, owner):"""Gets the text of the specified object"""driver = obj.driverWebDriverWait(driver, 100).until(lambda driver: driver.find_element_by_name(self.locator))element = driver.find_element_by_name(self.locator)return element.get_attribute("value")
6.4. 定位器
其中一個做法是,從它們正在使用的地方分離定位字符。在這個例子中,同一頁面的定位器屬于同一個類。
這個?locators.py
?看起來像這樣:
from selenium.webdriver.common.by import Byclass MainPageLocators(object):"""A class for main page locators. All main page locators should come here"""GO_BUTTON = (By.ID, 'submit')class SearchResultsPageLocators(object):"""A class for search results locators. All search results locators should come here"""pass
?
7. WebDriver API
Note
這不是一個官方的文檔. 但是你可以在這訪問官方文檔:?官方文檔.
這一章包含所有的 Selenium WebDriver 接口.
Recommended Import Style
The API definitions in this chapter shows the absolute location of classes. However the recommended import style is as given below:
from selenium import webdriver
Then, you can access the classes like this:
webdriver.Firefox webdriver.FirefoxProfile webdriver.Chrome webdriver.ChromeOptions webdriver.Ie webdriver.Opera webdriver.PhantomJS webdriver.Remote webdriver.DesiredCapabilities webdriver.ActionChains webdriver.TouchActions webdriver.Proxy
The special keys class (Keys
) can be imported like this:
from selenium.webdriver.common.keys import Keys
The exception classes can be imported like this (Replace the?TheNameOfTheExceptionClass
?with actual class name given below):
from selenium.common.exceptions import [TheNameOfTheExceptionClass]
Conventions used in the API
Some attributes are callable (or methods) and others are non-callable (properties). All the callable attributes are ending with round brackets.
Here is an example for property:
current_url
URL of the current loaded page.
Usage:
driver.current_url
Here is an example for a method:
close()
Closes the current window.
Usage:
driver.close()
7.1. Exceptions
Exceptions that may happen in all the webdriver code.
exceptionselenium.common.exceptions.
ElementNotInteractableException
(msg=None,?screen=None,?stacktrace=None)
Bases:?selenium.common.exceptions.InvalidElementStateException
Thrown when an element is present in the DOM but interactions with that element will hit another element do to paint order
exceptionselenium.common.exceptions.
ElementNotSelectableException
(msg=None,?screen=None,?stacktrace=None)
Bases:?selenium.common.exceptions.InvalidElementStateException
Thrown when trying to select an unselectable element.
For example, selecting a ‘script’ element.
exceptionselenium.common.exceptions.
ElementNotVisibleException
(msg=None,?screen=None,?stacktrace=None)
Bases:?selenium.common.exceptions.InvalidElementStateException
Thrown when an element is present on the DOM, but it is not visible, and so is not able to be interacted with.
Most commonly encountered when trying to click or read text of an element that is hidden from view.
exceptionselenium.common.exceptions.
ErrorInResponseException
(response,?msg)
Bases:?selenium.common.exceptions.WebDriverException
Thrown when an error has occurred on the server side.
This may happen when communicating with the firefox extension or the remote driver server.
exceptionselenium.common.exceptions.
ImeActivationFailedException
(msg=None,?screen=None,?stacktrace=None)
Bases:?selenium.common.exceptions.WebDriverException
Thrown when activating an IME engine has failed.
exceptionselenium.common.exceptions.
ImeNotAvailableException
(msg=None,?screen=None,?stacktrace=None)
Bases:?selenium.common.exceptions.WebDriverException
Thrown when IME support is not available. This exception is thrown for every IME-related method call if IME support is not available on the machine.
exceptionselenium.common.exceptions.
InvalidArgumentException
(msg=None,?screen=None,?stacktrace=None)
Bases:?selenium.common.exceptions.WebDriverException
The arguments passed to a command are either invalid or malformed.
exceptionselenium.common.exceptions.
InvalidCookieDomainException
(msg=None,?screen=None,?stacktrace=None)
Bases:?selenium.common.exceptions.WebDriverException
Thrown when attempting to add a cookie under a different domain than the current URL.
exceptionselenium.common.exceptions.
InvalidElementStateException
(msg=None,?screen=None,?stacktrace=None)
Bases:?selenium.common.exceptions.WebDriverException
exceptionselenium.common.exceptions.
InvalidSelectorException
(msg=None,?screen=None,?stacktrace=None)
Bases:?selenium.common.exceptions.NoSuchElementException
Thrown when the selector which is used to find an element does not return a WebElement. Currently this only happens when the selector is an xpath expression and it is either syntactically invalid (i.e. it is not a xpath expression) or the expression does not select WebElements (e.g. “count(//input)”).
exceptionselenium.common.exceptions.
InvalidSwitchToTargetException
(msg=None,?screen=None,?stacktrace=None)
Bases:?selenium.common.exceptions.WebDriverException
Thrown when frame or window target to be switched doesn’t exist.
exceptionselenium.common.exceptions.
MoveTargetOutOfBoundsException
(msg=None,?screen=None,?stacktrace=None)
Bases:?selenium.common.exceptions.WebDriverException
Thrown when the target provided to the?ActionsChains?move() method is invalid, i.e. out of document.
exceptionselenium.common.exceptions.
NoAlertPresentException
(msg=None,?screen=None,?stacktrace=None)
Bases:?selenium.common.exceptions.WebDriverException
Thrown when switching to no presented alert.
This can be caused by calling an operation on the Alert() class when an alert is not yet on the screen.
exceptionselenium.common.exceptions.
NoSuchAttributeException
(msg=None,?screen=None,?stacktrace=None)
Bases:?selenium.common.exceptions.WebDriverException
Thrown when the attribute of element could not be found.
You may want to check if the attribute exists in the particular browser you are testing against. Some browsers may have different property names for the same property. (IE8’s .innerText vs. Firefox .textContent)
exceptionselenium.common.exceptions.
NoSuchElementException
(msg=None,?screen=None,?stacktrace=None)
Bases:?selenium.common.exceptions.WebDriverException
Thrown when element could not be found.
If you encounter this exception, you may want to check the following:
- Check your selector used in your find_by...
- Element may not yet be on the screen at the time of the find operation, (webpage is still loading) see selenium.webdriver.support.wait.WebDriverWait() for how to write a wait wrapper to wait for an element to appear.
exceptionselenium.common.exceptions.
NoSuchFrameException
(msg=None,?screen=None,?stacktrace=None)
Bases:?selenium.common.exceptions.InvalidSwitchToTargetException
Thrown when frame target to be switched doesn’t exist.
exceptionselenium.common.exceptions.
NoSuchWindowException
(msg=None,?screen=None,?stacktrace=None)
Bases:?selenium.common.exceptions.InvalidSwitchToTargetException
Thrown when window target to be switched doesn’t exist.
To find the current set of active window handles, you can get a list of the active window handles in the following way:
print driver.window_handles
exceptionselenium.common.exceptions.
RemoteDriverServerException
(msg=None,?screen=None,?stacktrace=None)
Bases:?selenium.common.exceptions.WebDriverException
exceptionselenium.common.exceptions.
StaleElementReferenceException
(msg=None,?screen=None,?stacktrace=None)
Bases:?selenium.common.exceptions.WebDriverException
Thrown when a reference to an element is now “stale”.
Stale means the element no longer appears on the DOM of the page.
Possible causes of StaleElementReferenceException include, but not limited to:
- You are no longer on the same page, or the page may have refreshed since the element was located.
- The element may have been removed and re-added to the screen, since it was located. Such as an element being relocated. This can happen typically with a javascript framework when values are updated and the node is rebuilt.
- Element may have been inside an iframe or another context which was refreshed.
exceptionselenium.common.exceptions.
TimeoutException
(msg=None,?screen=None,?stacktrace=None)
Bases:?selenium.common.exceptions.WebDriverException
Thrown when a command does not complete in enough time.
exceptionselenium.common.exceptions.
UnableToSetCookieException
(msg=None,?screen=None,?stacktrace=None)
Bases:?selenium.common.exceptions.WebDriverException
Thrown when a driver fails to set a cookie.
exceptionselenium.common.exceptions.
UnexpectedAlertPresentException
(msg=None,?screen=None,?stacktrace=None,?alert_text=None)
Bases:?selenium.common.exceptions.WebDriverException
Thrown when an unexpected alert is appeared.
Usually raised when when an expected modal is blocking webdriver form executing any more commands.
exceptionselenium.common.exceptions.
UnexpectedTagNameException
(msg=None,?screen=None,?stacktrace=None)
Bases:?selenium.common.exceptions.WebDriverException
Thrown when a support class did not get an expected web element.
exceptionselenium.common.exceptions.
WebDriverException
(msg=None,?screen=None,?stacktrace=None)
Bases:?exceptions.Exception
Base webdriver exception.
7.2. Action Chains
The ActionChains implementation,
classselenium.webdriver.common.action_chains.
ActionChains
(driver)
Bases:?object
ActionChains are a way to automate low level interactions such as mouse movements, mouse button actions, key press, and context menu interactions. This is useful for doing more complex actions like hover over and drag and drop.
Generate user actions.
When you call methods for actions on the ActionChains object, the actions are stored in a queue in the ActionChains object. When you call perform(), the events are fired in the order they are queued up.
ActionChains can be used in a chain pattern:
menu = driver.find_element_by_css_selector(".nav") hidden_submenu = driver.find_element_by_css_selector(".nav #submenu1")ActionChains(driver).move_to_element(menu).click(hidden_submenu).perform()
Or actions can be queued up one by one, then performed.:
menu = driver.find_element_by_css_selector(".nav") hidden_submenu = driver.find_element_by_css_selector(".nav #submenu1")actions = ActionChains(driver) actions.move_to_element(menu) actions.click(hidden_submenu) actions.perform()
Either way, the actions are performed in the order they are called, one after another.
click
(on_element=None)
Clicks an element.
Args: |
|
---|
click_and_hold
(on_element=None)
Holds down the left mouse button on an element.
Args: |
|
---|
context_click
(on_element=None)
Performs a context-click (right click) on an element.
Args: |
|
---|
double_click
(on_element=None)
Double-clicks an element.
Args: |
|
---|
drag_and_drop
(source,?target)
Holds down the left mouse button on the source element,
then moves to the target element and releases the mouse button.
Args: |
|
---|
drag_and_drop_by_offset
(source,?xoffset,?yoffset)
Holds down the left mouse button on the source element,
then moves to the target offset and releases the mouse button.
Args: |
|
---|
key_down
(value,?element=None)
Sends a key press only, without releasing it.
Should only be used with modifier keys (Control, Alt and Shift).
Args: |
|
---|
Example, pressing ctrl+c:
ActionChains(driver).key_down(Keys.CONTROL).send_keys('c').key_up(Keys.CONTROL).perform()
key_up
(value,?element=None)
Releases a modifier key.
Args: |
|
---|
Example, pressing ctrl+c:
ActionChains(driver).key_down(Keys.CONTROL).send_keys('c').key_up(Keys.CONTROL).perform()
move_by_offset
(xoffset,?yoffset)
Moving the mouse to an offset from current mouse position.
Args: |
|
---|
move_to_element
(to_element)
Moving the mouse to the middle of an element.
Args: |
|
---|
move_to_element_with_offset
(to_element,?xoffset,?yoffset)
Move the mouse by an offset of the specified element.
Offsets are relative to the top-left corner of the element.
Args: |
|
---|
pause
(seconds)
Pause all inputs for the specified duration in seconds
perform
()
Performs all stored actions.
release
(on_element=None)
Releasing a held mouse button on an element.
Args: |
|
---|
reset_actions
()
Clears actions that are already stored on the remote end.
send_keys
(*keys_to_send)
Sends keys to current focused element.
Args: |
|
---|
send_keys_to_element
(element,?*keys_to_send)
Sends keys to an element.
Args: |
|
---|
7.3. Alerts
The Alert implementation.
classselenium.webdriver.common.alert.
Alert
(driver)
Bases:?object
Allows to work with alerts.
Use this class to interact with alert prompts. It contains methods for dismissing, accepting, inputting, and getting text from alert prompts.
Accepting / Dismissing alert prompts:
Alert(driver).accept() Alert(driver).dismiss()
Inputting a value into an alert prompt:
name_prompt = Alert(driver) name_prompt.send_keys(“Willian Shakesphere”) name_prompt.accept()
Reading a the text of a prompt for verification:
alert_text = Alert(driver).text self.assertEqual(“Do you wish to quit?”, alert_text)
accept
()
Accepts the alert available.
Usage:: Alert(driver).accept() # Confirm a alert dialog.
authenticate
(username,?password)
Send the username / password to an Authenticated dialog (like with Basic HTTP Auth). Implicitly ‘clicks ok’
Usage:: driver.switch_to.alert.authenticate(‘cheese’, ‘secretGouda’)
Args: | -username: string to be set in the username section of the dialog -password: string to be set in the password section of the dialog |
---|
dismiss
()
Dismisses the alert available.
send_keys
(keysToSend)
Send Keys to the Alert.
Args: |
|
---|
text
Gets the text of the Alert.
7.4. Special Keys
The Keys implementation.
classselenium.webdriver.common.keys.
Keys
Bases:?object
Set of special keys codes.
ADD
= u'\ue025'
ALT
= u'\ue00a'
ARROW_DOWN
= u'\ue015'
ARROW_LEFT
= u'\ue012'
ARROW_RIGHT
= u'\ue014'
ARROW_UP
= u'\ue013'
BACKSPACE
= u'\ue003'
BACK_SPACE
= u'\ue003'
CANCEL
= u'\ue001'
CLEAR
= u'\ue005'
COMMAND
= u'\ue03d'
CONTROL
= u'\ue009'
DECIMAL
= u'\ue028'
DELETE
= u'\ue017'
DIVIDE
= u'\ue029'
DOWN
= u'\ue015'
END
= u'\ue010'
ENTER
= u'\ue007'
EQUALS
= u'\ue019'
ESCAPE
= u'\ue00c'
F1
= u'\ue031'
F10
= u'\ue03a'
F11
= u'\ue03b'
F12
= u'\ue03c'
F2
= u'\ue032'
F3
= u'\ue033'
F4
= u'\ue034'
F5
= u'\ue035'
F6
= u'\ue036'
F7
= u'\ue037'
F8
= u'\ue038'
F9
= u'\ue039'
HELP
= u'\ue002'
HOME
= u'\ue011'
INSERT
= u'\ue016'
LEFT
= u'\ue012'
LEFT_ALT
= u'\ue00a'
LEFT_CONTROL
= u'\ue009'
LEFT_SHIFT
= u'\ue008'
META
= u'\ue03d'
MULTIPLY
= u'\ue024'
NULL
= u'\ue000'
NUMPAD0
= u'\ue01a'
NUMPAD1
= u'\ue01b'
NUMPAD2
= u'\ue01c'
NUMPAD3
= u'\ue01d'
NUMPAD4
= u'\ue01e'
NUMPAD5
= u'\ue01f'
NUMPAD6
= u'\ue020'
NUMPAD7
= u'\ue021'
NUMPAD8
= u'\ue022'
NUMPAD9
= u'\ue023'
PAGE_DOWN
= u'\ue00f'
PAGE_UP
= u'\ue00e'
PAUSE
= u'\ue00b'
RETURN
= u'\ue006'
RIGHT
= u'\ue014'
SEMICOLON
= u'\ue018'
SEPARATOR
= u'\ue026'
SHIFT
= u'\ue008'
SPACE
= u'\ue00d'
SUBTRACT
= u'\ue027'
TAB
= u'\ue004'
UP
= u'\ue013'
7.5. Locate elements By
These are the attributes which can be used to locate elements. See the?查找元素?chapter for example usages.
The By implementation.
classselenium.webdriver.common.by.
By
Bases:?object
Set of supported locator strategies.
CLASS_NAME
= 'class name'
CSS_SELECTOR
= 'css selector'
ID
= 'id'
LINK_TEXT
= 'link text'
NAME
= 'name'
PARTIAL_LINK_TEXT
= 'partial link text'
TAG_NAME
= 'tag name'
XPATH
= 'xpath'
7.6. Desired Capabilities
See the?使用遠程 Selenium WebDriver?section for example usages of desired capabilities.
The Desired Capabilities implementation.
classselenium.webdriver.common.desired_capabilities.
DesiredCapabilities
Bases:?object
Set of default supported desired capabilities.
Use this as a starting point for creating a desired capabilities object for requesting remote webdrivers for connecting to selenium server or selenium grid.
Usage Example:
from selenium import webdriverselenium_grid_url = "http://198.0.0.1:4444/wd/hub"# Create a desired capabilities object as a starting point. capabilities = DesiredCapabilities.FIREFOX.copy() capabilities['platform'] = "WINDOWS" capabilities['version'] = "10"# Instantiate an instance of Remote WebDriver with the desired capabilities. driver = webdriver.Remote(desired_capabilities=capabilities,command_executor=selenium_grid_url)
Note: Always use ‘.copy()’ on the DesiredCapabilities object to avoid the side effects of altering the Global class instance.
ANDROID
= {'platform': 'ANDROID', 'browserName': 'android', 'version': ''}
CHROME
= {'platform': 'ANY', 'browserName': 'chrome', 'version': ''}
EDGE
= {'platform': 'WINDOWS', 'browserName': 'MicrosoftEdge', 'version': ''}
FIREFOX
= {'acceptInsecureCerts': True, 'browserName': 'firefox', 'marionette': True}
HTMLUNIT
= {'platform': 'ANY', 'browserName': 'htmlunit', 'version': ''}
HTMLUNITWITHJS
= {'platform': 'ANY', 'browserName': 'htmlunit', 'version': 'firefox', 'javascriptEnabled': True}
INTERNETEXPLORER
= {'platform': 'WINDOWS', 'browserName': 'internet explorer', 'version': ''}
IPAD
= {'platform': 'MAC', 'browserName': 'iPad', 'version': ''}
IPHONE
= {'platform': 'MAC', 'browserName': 'iPhone', 'version': ''}
OPERA
= {'platform': 'ANY', 'browserName': 'opera', 'version': ''}
PHANTOMJS
= {'platform': 'ANY', 'browserName': 'phantomjs', 'version': '', 'javascriptEnabled': True}
SAFARI
= {'platform': 'MAC', 'browserName': 'safari', 'version': ''}
7.7. Utilities
The Utils methods.
selenium.webdriver.common.utils.
find_connectable_ip
(host,?port=None)
Resolve a hostname to an IP, preferring IPv4 addresses.
We prefer IPv4 so that we don’t change behavior from previous IPv4-only implementations, and because some drivers (e.g., FirefoxDriver) do not support IPv6 connections.
If the optional port number is provided, only IPs that listen on the given port are considered.
Args: |
|
---|---|
Returns: | A single IP address, as a string. If any IPv4 address is found, one is returned. Otherwise, if any IPv6 address is found, one is returned. If neither, then None is returned. |
selenium.webdriver.common.utils.
free_port
()
Determines a free port using sockets.
selenium.webdriver.common.utils.
is_connectable
(port,?host='localhost')
Tries to connect to the server at port to see if it is running.
Args: |
|
---|
selenium.webdriver.common.utils.
is_url_connectable
(port)
Tries to connect to the HTTP server at /status path and specified port to see if it responds successfully.
Args: |
|
---|
selenium.webdriver.common.utils.
join_host_port
(host,?port)
Joins a hostname and port together.
This is a minimal implementation intended to cope with IPv6 literals. For example, _join_host_port(‘::1’, 80) == ‘[::1]:80’.
Args: |
|
---|
selenium.webdriver.common.utils.
keys_to_typing
(value)
Processes the values that will be typed in the element.
7.8. Firefox WebDriver
classselenium.webdriver.firefox.webdriver.
WebDriver
(firefox_profile=None,?firefox_binary=None,?timeout=30,?capabilities=None,?proxy=None,?executable_path='geckodriver',?firefox_options=None,?log_path='geckodriver.log')
Bases:?selenium.webdriver.remote.webdriver.WebDriver
context
(*args,?**kwds)
Sets the context that Selenium commands are running in using a?with?statement. The state of the context on the server is saved before entering the block, and restored upon exiting it.
Parameters: | context?– Context, may be one of the class properties?CONTEXT_CHROME?or?CONTEXT_CONTENT. |
---|
Usage example:
with selenium.context(selenium.CONTEXT_CHROME):# chrome scope... do stuff ...
install_addon
(path,?temporary=None)
Installs Firefox addon.
Returns identifier of installed addon. This identifier can later be used to uninstall addon.
Parameters: | path?– Absolute path to the addon that will be installed. |
---|---|
Usage: | driver.install_addon(‘/path/to/firebug.xpi’) |
quit
()
Quits the driver and close every associated window.
set_context
(context)
uninstall_addon
(identifier)
Uninstalls Firefox addon using its identifier.
Usage: | driver.uninstall_addon('addon@foo.com‘) |
---|
CONTEXT_CHROME
= 'chrome'
CONTEXT_CONTENT
= 'content'
NATIVE_EVENTS_ALLOWED
= True
firefox_profile
7.9. Chrome WebDriver
classselenium.webdriver.chrome.webdriver.
WebDriver
(executable_path='chromedriver',?port=0,?chrome_options=None,?service_args=None,?desired_capabilities=None,?service_log_path=None)
Bases:?selenium.webdriver.remote.webdriver.WebDriver
Controls the ChromeDriver and allows you to drive the browser.
You will need to download the ChromeDriver executable from?http://chromedriver.storage.googleapis.com/index.html
create_options
()
get_network_conditions
()
Gets Chrome network emulation settings.
Returns: | A dict. For example: {‘latency’: 4, ‘download_throughput’: 2, ‘upload_throughput’: 2, ‘offline’: False} |
---|
launch_app
(id)
Launches Chrome app specified by id.
quit
()
Closes the browser and shuts down the ChromeDriver executable that is started when starting the ChromeDriver
set_network_conditions
(**network_conditions)
Sets Chrome network emulation settings.
Args: |
|
---|---|
Usage: | driver.set_network_conditions( offline=False, latency=5, # additional latency (ms) download_throughput=500 * 1024, # maximal throughput upload_throughput=500 * 1024) # maximal throughput Note: ‘throughput’ can be used to set both (for download and upload). |
7.10. Remote WebDriver
The WebDriver implementation.
classselenium.webdriver.remote.webdriver.
WebDriver
(command_executor='http://127.0.0.1:4444/wd/hub',?desired_capabilities=None,?browser_profile=None,?proxy=None,?keep_alive=False,?file_detector=None)
Bases:?object
Controls a browser by sending commands to a remote server. This server is expected to be running the WebDriver wire protocol as defined at?https://github.com/SeleniumHQ/selenium/wiki/JsonWireProtocol
Attributes: |
|
---|
add_cookie
(cookie_dict)
Adds a cookie to your current session.
Args: |
|
---|
Usage:
driver.add_cookie({‘name’ : ‘foo’, ‘value’ : ‘bar’}) driver.add_cookie({‘name’ : ‘foo’, ‘value’ : ‘bar’, ‘path’ : ‘/’}) driver.add_cookie({‘name’ : ‘foo’, ‘value’ : ‘bar’, ‘path’ : ‘/’, ‘secure’:True})
back
()
Goes one step backward in the browser history.
Usage: | driver.back() |
---|
close
()
Closes the current window.
Usage: | driver.close() |
---|
create_web_element
(element_id)
Creates a web element with the specified?element_id.
delete_all_cookies
()
Delete all cookies in the scope of the session.
Usage: | driver.delete_all_cookies() |
---|
delete_cookie
(name)
Deletes a single cookie with the given name.
Usage: | driver.delete_cookie(‘my_cookie’) |
---|
execute
(driver_command,?params=None)
Sends a command to be executed by a command.CommandExecutor.
Args: |
|
---|---|
Returns: | The command’s JSON response loaded into a dictionary object. |
execute_async_script
(script,?*args)
Asynchronously Executes JavaScript in the current window/frame.
Args: |
|
---|---|
Usage: | driver.execute_async_script(‘document.title’) |
execute_script
(script,?*args)
Synchronously Executes JavaScript in the current window/frame.
Args: |
|
---|---|
Usage: | driver.execute_script(‘document.title’) |
file_detector_context
(*args,?**kwds)
Overrides the current file detector (if necessary) in limited context. Ensures the original file detector is set afterwards.
Example:
with webdriver.file_detector_context(UselessFileDetector):
someinput.send_keys(‘/etc/hosts’)
Args: |
|
---|
find_element
(by='id',?value=None)
‘Private’ method used by the find_element_by_* methods.
Usage: | Use the corresponding find_element_by_* instead of this. |
---|---|
Return type: | WebElement |
find_element_by_class_name
(name)
Finds an element by class name.
Args: |
|
---|---|
Usage: | driver.find_element_by_class_name(‘foo’) |
find_element_by_css_selector
(css_selector)
Finds an element by css selector.
Args: |
|
---|---|
Usage: | driver.find_element_by_css_selector(‘#foo’) |
find_element_by_id
(id_)
Finds an element by id.
Args: |
|
---|---|
Usage: | driver.find_element_by_id(‘foo’) |
find_element_by_link_text
(link_text)
Finds an element by link text.
Args: |
|
---|---|
Usage: | driver.find_element_by_link_text(‘Sign In’) |
find_element_by_name
(name)
Finds an element by name.
Args: |
|
---|---|
Usage: | driver.find_element_by_name(‘foo’) |
find_element_by_partial_link_text
(link_text)
Finds an element by a partial match of its link text.
Args: |
|
---|---|
Usage: | driver.find_element_by_partial_link_text(‘Sign’) |
find_element_by_tag_name
(name)
Finds an element by tag name.
Args: |
|
---|---|
Usage: | driver.find_element_by_tag_name(‘foo’) |
find_element_by_xpath
(xpath)
Finds an element by xpath.
Args: |
|
---|---|
Usage: | driver.find_element_by_xpath(‘//div/td[1]’) |
find_elements
(by='id',?value=None)
‘Private’ method used by the find_elements_by_* methods.
Usage: | Use the corresponding find_elements_by_* instead of this. |
---|---|
Return type: | list of WebElement |
find_elements_by_class_name
(name)
Finds elements by class name.
Args: |
|
---|---|
Usage: | driver.find_elements_by_class_name(‘foo’) |
find_elements_by_css_selector
(css_selector)
Finds elements by css selector.
Args: |
|
---|---|
Usage: | driver.find_elements_by_css_selector(‘.foo’) |
find_elements_by_id
(id_)
Finds multiple elements by id.
Args: |
|
---|---|
Usage: | driver.find_elements_by_id(‘foo’) |
find_elements_by_link_text
(text)
Finds elements by link text.
Args: |
|
---|---|
Usage: | driver.find_elements_by_link_text(‘Sign In’) |
find_elements_by_name
(name)
Finds elements by name.
Args: |
|
---|---|
Usage: | driver.find_elements_by_name(‘foo’) |
find_elements_by_partial_link_text
(link_text)
Finds elements by a partial match of their link text.
Args: |
|
---|---|
Usage: | driver.find_element_by_partial_link_text(‘Sign’) |
find_elements_by_tag_name
(name)
Finds elements by tag name.
Args: |
|
---|---|
Usage: | driver.find_elements_by_tag_name(‘foo’) |
find_elements_by_xpath
(xpath)
Finds multiple elements by xpath.
Args: |
|
---|---|
Usage: | driver.find_elements_by_xpath(“//div[contains(@class, ‘foo’)]”) |
forward
()
Goes one step forward in the browser history.
Usage: | driver.forward() |
---|
fullscreen_window
()
Invokes the window manager-specific ‘full screen’ operation
get
(url)
Loads a web page in the current browser session.
get_cookie
(name)
Get a single cookie by name. Returns the cookie if found, None if not.
Usage: | driver.get_cookie(‘my_cookie’) |
---|
get_cookies
()
Returns a set of dictionaries, corresponding to cookies visible in the current session.
Usage: | driver.get_cookies() |
---|
get_log
(log_type)
Gets the log for a given log type
Args: |
|
---|---|
Usage: | driver.get_log(‘browser’) driver.get_log(‘driver’) driver.get_log(‘client’) driver.get_log(‘server’) |
get_screenshot_as_base64
()
Gets the screenshot of the current window as a base64 encoded string
which is useful in embedded images in HTML.
Usage: | driver.get_screenshot_as_base64() |
---|
get_screenshot_as_file
(filename)
Saves a screenshot of the current window to a PNG image file. Returns
False if there is any IOError, else returns True. Use full paths in your filename.
Args: |
|
---|---|
Usage: | driver.get_screenshot_as_file(‘/Screenshots/foo.png’) |
get_screenshot_as_png
()
Gets the screenshot of the current window as a binary data.
Usage: | driver.get_screenshot_as_png() |
---|
get_window_position
(windowHandle='current')
Gets the x,y position of the current window.
Usage: | driver.get_window_position() |
---|
get_window_rect
()
Gets the x, y coordinates of the window as well as height and width of the current window.
Usage: | driver.get_window_rect() |
---|
get_window_size
(windowHandle='current')
Gets the width and height of the current window.
Usage: | driver.get_window_size() |
---|
implicitly_wait
(time_to_wait)
Sets a sticky timeout to implicitly wait for an element to be found,
or a command to complete. This method only needs to be called one time per session. To set the timeout for calls to execute_async_script, see set_script_timeout.
Args: |
|
---|---|
Usage: | driver.implicitly_wait(30) |
maximize_window
()
Maximizes the current window that webdriver is using
minimize_window
()
Invokes the window manager-specific ‘minimize’ operation
quit
()
Quits the driver and closes every associated window.
Usage: | driver.quit() |
---|
refresh
()
Refreshes the current page.
Usage: | driver.refresh() |
---|
save_screenshot
(filename)
Saves a screenshot of the current window to a PNG image file. Returns
False if there is any IOError, else returns True. Use full paths in your filename.
Args: |
|
---|---|
Usage: | driver.save_screenshot(‘/Screenshots/foo.png’) |
set_page_load_timeout
(time_to_wait)
Set the amount of time to wait for a page load to complete
before throwing an error.
Args: |
|
---|---|
Usage: | driver.set_page_load_timeout(30) |
set_script_timeout
(time_to_wait)
Set the amount of time that the script should wait during an
execute_async_script call before throwing an error.
Args: |
|
---|---|
Usage: | driver.set_script_timeout(30) |
set_window_position
(x,?y,?windowHandle='current')
Sets the x,y position of the current window. (window.moveTo)
Args: |
|
---|---|
Usage: | driver.set_window_position(0,0) |
set_window_rect
(x=None,?y=None,?width=None,?height=None)
Sets the x, y coordinates of the window as well as height and width of the current window.
Usage: | driver.set_window_rect(x=10, y=10) driver.set_window_rect(width=100, height=200) driver.set_window_rect(x=10, y=10, width=100, height=200) |
---|
set_window_size
(width,?height,?windowHandle='current')
Sets the width and height of the current window. (window.resizeTo)
Args: |
|
---|---|
Usage: | driver.set_window_size(800,600) |
start_client
()
Called before starting a new session. This method may be overridden to define custom startup behavior.
start_session
(capabilities,?browser_profile=None)
Creates a new session with the desired capabilities.
Args: |
|
---|
stop_client
()
Called after executing a quit command. This method may be overridden to define custom shutdown behavior.
switch_to_active_element
()
Deprecated use driver.switch_to.active_element
switch_to_alert
()
Deprecated use driver.switch_to.alert
switch_to_default_content
()
Deprecated use driver.switch_to.default_content
switch_to_frame
(frame_reference)
Deprecated use driver.switch_to.frame
switch_to_window
(window_name)
Deprecated use driver.switch_to.window
application_cache
Returns a ApplicationCache Object to interact with the browser app cache
current_url
Gets the URL of the current page.
Usage: | driver.current_url |
---|
current_window_handle
Returns the handle of the current window.
Usage: | driver.current_window_handle |
---|
desired_capabilities
returns the drivers current desired capabilities being used
file_detector
log_types
Gets a list of the available log types
Usage: | driver.log_types |
---|
mobile
name
Returns the name of the underlying browser for this instance.
Usage: |
|
---|
orientation
Gets the current orientation of the device
Usage: | orientation = driver.orientation |
---|
page_source
Gets the source of the current page.
Usage: | driver.page_source |
---|
switch_to
title
Returns the title of the current page.
Usage: | driver.title |
---|
window_handles
Returns the handles of all windows within the current session.
Usage: | driver.window_handles |
---|
7.11. WebElement
classselenium.webdriver.remote.webelement.
WebElement
(parent,?id_,?w3c=False)
Bases:?object
Represents a DOM element.
Generally, all interesting operations that interact with a document will be performed through this interface.
All method calls will do a freshness check to ensure that the element reference is still valid. This essentially determines whether or not the element is still attached to the DOM. If this test fails, then an?StaleElementReferenceException
?is thrown, and all future calls to this instance will fail.
clear
()
Clears the text if it’s a text entry element.
click
()
Clicks the element.
find_element
(by='id',?value=None)
find_element_by_class_name
(name)
Finds element within this element’s children by class name.
Args: |
|
---|
find_element_by_css_selector
(css_selector)
Finds element within this element’s children by CSS selector.
Args: |
|
---|
find_element_by_id
(id_)
Finds element within this element’s children by ID.
Args: |
|
---|
find_element_by_link_text
(link_text)
Finds element within this element’s children by visible link text.
Args: |
|
---|
find_element_by_name
(name)
Finds element within this element’s children by name.
Args: |
|
---|
find_element_by_partial_link_text
(link_text)
Finds element within this element’s children by partially visible link text.
Args: |
|
---|
find_element_by_tag_name
(name)
Finds element within this element’s children by tag name.
Args: |
|
---|
find_element_by_xpath
(xpath)
Finds element by xpath.
Args: | xpath - xpath of element to locate. “//input[@class=’myelement’]” |
---|
Note: The base path will be relative to this element’s location.
This will select the first link under this element.
myelement.find_elements_by_xpath(".//a")
However, this will select the first link on the page.
myelement.find_elements_by_xpath("//a")
find_elements
(by='id',?value=None)
find_elements_by_class_name
(name)
Finds a list of elements within this element’s children by class name.
Args: |
|
---|
find_elements_by_css_selector
(css_selector)
Finds a list of elements within this element’s children by CSS selector.
Args: |
|
---|
find_elements_by_id
(id_)
Finds a list of elements within this element’s children by ID.
Args: |
|
---|
find_elements_by_link_text
(link_text)
Finds a list of elements within this element’s children by visible link text.
Args: |
|
---|
find_elements_by_name
(name)
Finds a list of elements within this element’s children by name.
Args: |
|
---|
find_elements_by_partial_link_text
(link_text)
Finds a list of elements within this element’s children by link text.
Args: |
|
---|
find_elements_by_tag_name
(name)
Finds a list of elements within this element’s children by tag name.
Args: |
|
---|
find_elements_by_xpath
(xpath)
Finds elements within the element by xpath.
Args: |
|
---|
Note: The base path will be relative to this element’s location.
This will select all links under this element.
myelement.find_elements_by_xpath(".//a")
However, this will select all links in the page itself.
myelement.find_elements_by_xpath("//a")
get_attribute
(name)
Gets the given attribute or property of the element.
This method will first try to return the value of a property with the given name. If a property with that name doesn’t exist, it returns the value of the attribute with the same name. If there’s no attribute with that name,?None
?is returned.
Values which are considered truthy, that is equals “true” or “false”, are returned as booleans. All other non-None
?values are returned as strings. For attributes or properties which do not exist,?None
?is returned.
Args: |
|
---|
Example:
# Check if the "active" CSS class is applied to an element. is_active = "active" in target_element.get_attribute("class")
get_property
(name)
Gets the given property of the element.
Args: |
|
---|
Example:
# Check if the "active" CSS class is applied to an element. text_length = target_element.get_property("text_length")
is_displayed
()
Whether the element is visible to a user.
is_enabled
()
Returns whether the element is enabled.
is_selected
()
Returns whether the element is selected.
Can be used to check if a checkbox or radio button is selected.
screenshot
(filename)
Saves a screenshot of the current element to a PNG image file. Returns
False if there is any IOError, else returns True. Use full paths in your filename.
Args: |
|
---|---|
Usage: | element.screenshot(‘/Screenshots/foo.png’) |
send_keys
(*value)
Simulates typing into the element.
Args: |
|
---|
Use this to send simple key events or to fill out form fields:
form_textfield = driver.find_element_by_name('username') form_textfield.send_keys("admin")
This can also be used to set file inputs.
file_input = driver.find_element_by_name('profilePic') file_input.send_keys("path/to/profilepic.gif") # Generally it's better to wrap the file path in one of the methods # in os.path to return the actual path to support cross OS testing. # file_input.send_keys(os.path.abspath("path/to/profilepic.gif"))
submit
()
Submits a form.
value_of_css_property
(property_name)
The value of a CSS property.
id
Internal ID used by selenium.
This is mainly for internal use. Simple use cases such as checking if 2 webelements refer to the same element, can be done using?==
:
if element1 == element2:print("These 2 are equal")
location
The location of the element in the renderable canvas.
location_once_scrolled_into_view
THIS PROPERTY MAY CHANGE WITHOUT WARNING. Use this to discover where on the screen an element is so that we can click it. This method should cause the element to be scrolled into view.
Returns the top lefthand corner location on the screen, or?None
?if the element is not visible.
parent
Internal reference to the WebDriver instance this element was found from.
rect
A dictionary with the size and location of the element.
screenshot_as_base64
Gets the screenshot of the current element as a base64 encoded string.
Usage: | img_b64 = element.screenshot_as_base64 |
---|
screenshot_as_png
Gets the screenshot of the current element as a binary data.
Usage: | element_png = element.screenshot_as_png |
---|
size
The size of the element.
tag_name
This element’s?tagName
?property.
text
The text of the element.
7.12. UI Support
classselenium.webdriver.support.select.
Select
(webelement)
Bases:?object
deselect_all
()
Clear all selected entries. This is only valid when the SELECT supports multiple selections. throws NotImplementedError If the SELECT does not support multiple selections
deselect_by_index
(index)
Deselect the option at the given index. This is done by examing the “index” attribute of an element, and not merely by counting.
Args: |
throws NoSuchElementException If there is no option with specisied index in SELECT |
---|
deselect_by_value
(value)
Deselect all options that have a value matching the argument. That is, when given “foo” this would deselect an option like:
<option value=”foo”>Bar</option>
Args: |
throws NoSuchElementException If there is no option with specisied value in SELECT |
---|
deselect_by_visible_text
(text)
Deselect all options that display text matching the argument. That is, when given “Bar” this would deselect an option like:
<option value=”foo”>Bar</option>
Args: |
|
---|
select_by_index
(index)
Select the option at the given index. This is done by examing the “index” attribute of an element, and not merely by counting.
Args: |
|
---|
throws NoSuchElementException If there is no option with specisied index in SELECT
select_by_value
(value)
Select all options that have a value matching the argument. That is, when given “foo” this would select an option like:
<option value=”foo”>Bar</option>
Args: |
|
---|
throws NoSuchElementException If there is no option with specisied value in SELECT
select_by_visible_text
(text)
Select all options that display text matching the argument. That is, when given “Bar” this would select an option like:
<option value=”foo”>Bar</option>
Args: |
throws NoSuchElementException If there is no option with specisied text in SELECT |
---|
all_selected_options
Returns a list of all selected options belonging to this select tag
first_selected_option
The first selected option in this select tag (or the currently selected option in a normal select)
options
Returns a list of all options belonging to this select tag
classselenium.webdriver.support.wait.
WebDriverWait
(driver,?timeout,?poll_frequency=0.5,?ignored_exceptions=None)
Bases:?object
until
(method,?message='')
Calls the method provided with the driver as an argument until the return value is not False.
until_not
(method,?message='')
Calls the method provided with the driver as an argument until the return value is False.
7.13. Color Support
classselenium.webdriver.support.color.
Color
(red,?green,?blue,?alpha=1)
Bases:?object
Color conversion support class
Example:
from selenium.webdriver.support.color import Colorprint(Color.from_string('#00ff33').rgba) print(Color.from_string('rgb(1, 255, 3)').hex) print(Color.from_string('blue').rgba)
staticfrom_string
(str_)
hex
rgb
rgba
7.14. Expected conditions Support
classselenium.webdriver.support.expected_conditions.
alert_is_present
Bases:?object
Expect an alert to be present.
classselenium.webdriver.support.expected_conditions.
element_located_selection_state_to_be
(locator,?is_selected)
Bases:?object
An expectation to locate an element and check if the selection state specified is in that state. locator is a tuple of (by, path) is_selected is a boolean
classselenium.webdriver.support.expected_conditions.
element_located_to_be_selected
(locator)
Bases:?object
An expectation for the element to be located is selected. locator is a tuple of (by, path)
classselenium.webdriver.support.expected_conditions.
element_selection_state_to_be
(element,?is_selected)
Bases:?object
An expectation for checking if the given element is selected. element is WebElement object is_selected is a Boolean.”
classselenium.webdriver.support.expected_conditions.
element_to_be_clickable
(locator)
Bases:?object
An Expectation for checking an element is visible and enabled such that you can click it.
classselenium.webdriver.support.expected_conditions.
element_to_be_selected
(element)
Bases:?object
An expectation for checking the selection is selected. element is WebElement object
classselenium.webdriver.support.expected_conditions.
frame_to_be_available_and_switch_to_it
(locator)
Bases:?object
An expectation for checking whether the given frame is available to switch to. If the frame is available it switches the given driver to the specified frame.
classselenium.webdriver.support.expected_conditions.
invisibility_of_element_located
(locator)
Bases:?object
An Expectation for checking that an element is either invisible or not present on the DOM.
locator used to find the element
classselenium.webdriver.support.expected_conditions.
new_window_is_opened
(current_handles)
Bases:?object
An expectation that a new window will be opened and have the number of windows handles increase
classselenium.webdriver.support.expected_conditions.
number_of_windows_to_be
(num_windows)
Bases:?object
An expectation for the number of windows to be a certain value.
classselenium.webdriver.support.expected_conditions.
presence_of_all_elements_located
(locator)
Bases:?object
An expectation for checking that there is at least one element present on a web page. locator is used to find the element returns the list of WebElements once they are located
classselenium.webdriver.support.expected_conditions.
presence_of_element_located
(locator)
Bases:?object
An expectation for checking that an element is present on the DOM of a page. This does not necessarily mean that the element is visible. locator - used to find the element returns the WebElement once it is located
classselenium.webdriver.support.expected_conditions.
staleness_of
(element)
Bases:?object
Wait until an element is no longer attached to the DOM. element is the element to wait for. returns False if the element is still attached to the DOM, true otherwise.
classselenium.webdriver.support.expected_conditions.
text_to_be_present_in_element
(locator,?text_)
Bases:?object
An expectation for checking if the given text is present in the specified element. locator, text
classselenium.webdriver.support.expected_conditions.
text_to_be_present_in_element_value
(locator,?text_)
Bases:?object
An expectation for checking if the given text is present in the element’s locator, text
classselenium.webdriver.support.expected_conditions.
title_contains
(title)
Bases:?object
An expectation for checking that the title contains a case-sensitive substring. title is the fragment of title expected returns True when the title matches, False otherwise
classselenium.webdriver.support.expected_conditions.
title_is
(title)
Bases:?object
An expectation for checking the title of a page. title is the expected title, which must be an exact match returns True if the title matches, false otherwise.
classselenium.webdriver.support.expected_conditions.
url_changes
(url)
Bases:?object
An expectation for checking the current url. url is the expected url, which must not be an exact match returns True if the url is different, false otherwise.
classselenium.webdriver.support.expected_conditions.
url_contains
(url)
Bases:?object
An expectation for checking that the current url contains a case-sensitive substring. url is the fragment of url expected, returns True when the title matches, False otherwise
classselenium.webdriver.support.expected_conditions.
url_matches
(pattern)
Bases:?object
An expectation for checking the current url. pattern is the expected pattern, which must be an exact match returns True if the title matches, false otherwise.
classselenium.webdriver.support.expected_conditions.
url_to_be
(url)
Bases:?object
An expectation for checking the current url. url is the expected url, which must be an exact match returns True if the title matches, false otherwise.
classselenium.webdriver.support.expected_conditions.
visibility_of
(element)
Bases:?object
An expectation for checking that an element, known to be present on the DOM of a page, is visible. Visibility means that the element is not only displayed but also has a height and width that is greater than 0. element is the WebElement returns the (same) WebElement once it is visible
classselenium.webdriver.support.expected_conditions.
visibility_of_all_elements_located
(locator)
Bases:?object
An expectation for checking that all elements are present on the DOM of a page and visible. Visibility means that the elements are not only displayed but also has a height and width that is greater than 0. locator - used to find the elements returns the list of WebElements once they are located and visible
classselenium.webdriver.support.expected_conditions.
visibility_of_any_elements_located
(locator)
Bases:?object
An expectation for checking that there is at least one element visible on a web page. locator is used to find the element returns the list of WebElements once they are located
classselenium.webdriver.support.expected_conditions.
visibility_of_element_located
(locator)
Bases:?object
An expectation for checking that an element is present on the DOM of a page and visible. Visibility means that the element is not only displayed but also has a height and width that is greater than 0. locator - used to find the element returns the WebElement once it is located and visible