WebUI自动化,首先需要定位页面中待操作的元素,然后进行各种事件操作,这里我们首先介绍Selenium Python 如何定位页面元素,WebDriver 提供了一系列的方法。
定位单个页面元素(返回单个元素对象)
find_element_by_idfind_element_by_namefind_element_by_xpathfind_element_by_link_textfind_element_by_partial_link_textfind_element_by_tag_namefind_element_by_class_namefind_element_by_css_selector需要注意的是,上面的方法当匹配到多个对象时,只能返回定位到的第一个元素对象,当没有匹配到任何元素对象,则会抛出异常NoSuchElementException
定位页面元素组(返回元素对象列表)
find_elements_by_namefind_elements_by_xpathfind_elements_by_link_textfind_elements_by_partial_link_textfind_elements_by_tag_namefind_elements_by_class_namefind_elements_by_css_selectorHTML模板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>1.利用绝对路径定位
login_form = driver.find_element_by_xpath("/html/body/form[1]")2.利用元素属性定位
login_form = driver.find_element_by_xpath("//form[@id='loginForm']")3.层级与属性结合
username = driver.find_element_by_xpath("//form[@id='loginForm']/input[1]")4.使用逻辑运算符
clear_button = driver.find_element_by_xpath("//input[@name='continue'][@type='button']") clear_button = driver.find_element_by_xpath("//input[@name='continue' and @type='button']")
HTML模板Example2
<!DOCTYPE html> <html lang="en"> <body> <h1>Welcome</h1> <p class="content">Are you sure you want to do this?</p> <div id="detail"> <a href="continue.html" name="tj_continue" title="web" class="RecycleBin xz" id="continue">Continue</a> <a href="cancel.html" target="_blank">Cancel</a> </div> <a href="" name="index" target="_blank">index</a> </body> <html>1.通过class属性定位
content = driver.find_element_by_css_selector('p.content') continue_link = driver.find_element_by_css_selector('.RecycleBin.xz') continue_link = driver.find_element_by_css_selector('a.RecycleBin')2.通过id属性定位
continue_link = driver.find_element_by_css_selector('#continue')3.通过标签名定位
links = driver.find_elements_by_css_selector('a')4.通过父子关系定位
links=driver.find_elements_by_css_selector('div>a')5.通过兄弟关系定位
links=driver.find_elements_by_css_selector('div+a')6.通过属性定位
links=driver.find_elements_by_css_selector("[target=_blank]") continue_link = driver.find_element_by_css_selector('a[title="web"]')7.组合定位
driver.find_element_by_css_selector('div#detail>a.RecycleBin') driver.find_element_by_css_selector('div#detail>a[name=tj_continue]')from selenium import webdriver import os driver = webdriver.Chrome() file_path = 'file:///' + os.path.abspath('demo.html') driver.get(file_path) print(driver.find_element_by_css_selector('div#detail>a.RecycleBin').text) print(driver.find_element_by_css_selector('div#detail>a[name=tj_continue]').text) driver.close()
转载于:https://www.cnblogs.com/guanfuchang/p/7405677.html