Selenium with Python 003 - 頁面元素定位
阿新 • • 發佈:2017-08-26
imp itl util lin tro pytho for title name
WebUI自動化,首先需要定位頁面中待操作的元素,然後進行各種事件操作,這裏我們首先介紹Selenium Python 如何定位頁面元素,WebDriver 提供了一系列的方法。
定位單個頁面元素(返回單個元素對象)
- 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
需要註意的是,上面的方法當匹配到多個對象時,只能返回定位到的第一個元素對象,當沒有匹配到任何元素對象,則會拋出異常NoSuchElementException
定位頁面元素組(返回元素對象列表)
- 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
HTML模板Example1
<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>
通過id定位
login_form = driver.find_element_by_id(‘loginForm‘)
通過name定位
username = driver.find_element_by_name(‘username‘) password = driver.find_element_by_name(‘password‘)
通過xpath定位
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‘]")
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‘]")
clear_button = driver.find_element_by_xpath("//input[@name=‘continue‘][@type=‘button‘]") clear_button = driver.find_element_by_xpath("//form[@id=‘loginForm‘]/input[4]")
HTML模板Example2
<html> <body> <h1>Welcome</h1> <p class="content">Are you sure you want to do this?</p> <a href="continue.html" name="tj_continue" title="web" class="RecycleBin xz">Continue</a> <a href="cancel.html">Cancel</a> </body> <html>
通過鏈接文本定位
continue_link = driver.find_element_by_link_text(‘Continue‘)
continue_link = driver.find_element_by_partial_link_text(‘Conti‘)
通過標簽名定位
heading1 = driver.find_element_by_tag_name(‘h1‘)
通過class定位
content = driver.find_element_by_class_name(‘content‘)
通過css 選擇器定位
content = driver.find_element_by_css_selector(‘p.content‘)
continue_link = driver.find_element_by_css_selector("a[name=\"tj_continue\"]")
continue_link = driver.find_element_by_css_selector(‘a[title="web"]‘)
continue_link = driver.find_element_by_css_selector(‘a.RecycleBin‘)
Selenium with Python 003 - 頁面元素定位