[Software Testing] Selenium API Explanation

Table of contents

1. The first script

2. Positioning of elements

1. ID and name positioning

2. Positioning of tag name and class name

3. CSS positioning

4. XPath positioning

5. Link text positioning

3. Operation of test objects

1. Mouse click and keyboard input

2. text gets the element text

3. Print information

4. Browser operation

1. Maximize the browser

2. Set the browser width and height

3. Operate the browser forward and backward

4. Control the browser scroll bar

5. Keyboard events

1. Usage of keyboard keys

2. Usage of keyboard key combinations

6. Mouse events

1. Position a group of elements

2. Multi-layer frame/window positioning

3. Hierarchical positioning

4. Drop-down box processing

5. Processing of alert, confirm and prompt

6. Enter the value


1. The first script

from selenium import webdriver
import time
browser = webdriver.Chrome()
time.sleep(3)
browser.get("http://www.baidu.com")
time.sleep(3)
browser.find_element_by_id("kw").send_keys("selenium")
time.sleep(3)
browser.find_element_by_id("su").click()
browser.quit()

coding = utf-8

You can add it or not. Developers like to add it to prevent garbled characters.

from selenium import webdriver

To use the functions in selenium's webdriver, first import the package

browser = webdriver.Chrome()

Which browser do we need to control? Chrome, of course, you can also change it to Ie or Firefox. The browser can be taken at will, but it will be used later to control the execution of various functions.

browser.find_element_by_id("kw").send_keys("selenium")

A control has several attributes id, name, (it can also be positioned in other ways). The id of the Baidu input box is called kw. I want to enter selenium in the input box.

browser.find_element_by_id("su").click()

The id of the searched button is called su, and I need to click the button (click()).

browser.quit()

Exit and close windows for each associated driver

2. Positioning of elements

The positioning of objects should be the core of automated testing. If you want to operate an object, you should first identify the object. An object is just like a person. He will have various characteristics (attributes). For example, we can find the person through his ID number, name, or which street, floor, or house number he lives in.

Then an object also has similar attributes, and we can find the object through this attribute.

Note: Regardless of which method is used, the uniqueness of this attribute on the page must be ensured.

webdriver provides a series of object positioning methods, the following are commonly used

id

name

class name

link text

partial link text

tag name

xpath

css selector

#coding=utf-8
from selenium import webdriver
import time
browser = webdriver.Chrome()
browser.get("http://www.baidu.com")
#########百度输入框的定位方式##########
#通过id 方式定位
browser.find_element_by_id("kw").send_keys("selenium")
#通过name 方式定位
browser.find_element_by_name("wd").send_keys("selenium")
#通过tag name 方式定位
browser.find_element_by_tag_name("input").send_keys("selenium") 不能成功,因为input太多了不唯一。
#通过class name 方式定位
browser.find_element_by_class_name("s_ipt").send_keys("selenium")
#通过CSS 方式定位
browser.find_element_by_css_selector("#kw").send_keys("selenium")
#通过xphan 方式定位
browser.find_element_by_xpath("//*[@id='kw']").send_keys("selenium")
############################################
browser.find_element_by_id("su").click()
time.sleep(3)
browser.quit()

1. ID and name positioning

id and name are our most commonly used positioning methods, because most controls have these two attributes, and when naming the id and name of the control, they generally use different names to make them meaningful. These two attributes make it very easy for us to find attributes on a page.

We found the attribute information of the Baidu input box through front-end tools, such as chrome's F12, as follows:

<input id="kw" class="s_ipt" type="text" maxlength="100" name="wd" autocomplete="off">

id="kw" Through the find_element_by_id("kw") function, the Baidu input box name="wd" can also be captured through the find_element_by_name("wd") function.

2. Positioning of tag name and class name

From the attribute information of the Baidu input box above, we can see that there are not only two attributes, id and name, such as class and tag name (tag name)

input is the name of a tag, which can be located through the find_element_by_tag_name("input") function. class="s_ipt", capture the Baidu input box through the find_element_by_class_name("s_ipt") function.

3. CSS positioning

CSS (Cascading Style Sheets) is a language used to describe the presentation of HTML and XML documents. CSS uses selectors to bind properties to page elements. These selectors can be used by Selenium as an additional targeting strategy.

4. XPath positioning

XPath is a language for locating elements in XML documents. Because HTML can be considered an implementation of XML, selenium users can use this powerful language to locate elements in web applications.

XPath extends the above id and name positioning methods to provide many possibilities. XPATH can be obtained by using Element-right-click-copy-copy xpath in Chrome's F12 developer mode.

5. Link text positioning

Sometimes it is not an input box or a button, but a text link. We can use link, but this method has been deprecated.

#coding=utf-8
from selenium import webdriver
browser = webdriver.Chrome()
browser.get("http://www.baidu.com")
browser.find_element_by_link_text("hao123").click()
browser.quit()

3. Operation of test objects

Because the recorded gif is too big and exceeds the upload limit of CSDN, I directly screenshot some pictures.

As mentioned earlier, a lot of knowledge is about positioning elements. Positioning is only the first step. After positioning, this element needs to be operated. Whether it is a mouse click or keyboard input, it depends on whether we are positioning a button or an input box.

Generally speaking, the more commonly used methods of operating objects in webdriver are as follows:

click click object

send_keys simulates key input on the object

clear clears the contents of the object, if possible

submit clears the object's contents, if possible

text is used to get the text information of the element

1. Mouse click and keyboard input

#coding=utf-8
from selenium import webdriver
import time
driver = webdriver.Chrome()
driver.get("http://www.baidu.com")
time.sleep(2)
driver.find_element_by_id("kw").send_keys("test")
time.sleep(2)
driver.find_element_by_id("kw").clear()
driver.find_element_by_id("kw").send_keys("selenium")
time.sleep(2)
#通过submit() 来操作
driver.find_element_by_id("su").submit()
time.sleep(3)
driver.quit()

 send_keys("xx") is used to enter xx content in an input box. click() is used to click a button. clear() is used to clear the content of the input box. For example, the Baidu input box has the message "Please enter keywords" by default. Another example is that our login box generally has default information such as "account number" and "password" by default. clear can help us clear this information.

2. text gets the element text

#coding=utf-8
from selenium import webdriver
import time
driver = webdriver.Chrome()
driver.get("http://www.baidu.com")
time.sleep(2)
#id = cp 元素的文本信息
data=driver.find_element_by_id("cp").text
print data #打印信息
time.sleep(3)
driver.quit()

3. Print information

#coding = utf-8
from selenium import webdriver
driver = webdriver.Chrome()
driver.get('http://www.baidu.com')
print(driver.title) # 把页面title 打印出来
print(driver.current_url) #打印url
driver.quit()

4. Browser operation

1. Maximize the browser

We know that the browser that is called to start is not full screen, so it will not affect the execution of the script, but sometimes it will affect the execution of our "viewing" script.

#coding=utf-8
from selenium import webdriver
import time
browser = webdriver.Chrome()
browser.get("http://www.baidu.com")
print "浏览器最大化"
browser.maximize_window() #将浏览器最大化显示
time.sleep(2)
browser.find_element_by_id("kw").send_keys("selenium")
browser.find_element_by_id("su").click()
time.sleep(3)
browser.quit()

2. Set the browser width and height

#coding=utf-8
from selenium import webdriver
import time
browser = webdriver.Chrome()
browser.get("http://www.baidu.com")
time.sleep(2)
#参数数字为像素点
browser.set_window_size(500, 500)
time.sleep(3)
browser.quit()

3. Operate the browser forward and backward

#coding=utf-8
from selenium import webdriver
import time
browser = webdriver.Chrome()
#访问百度首页
first_url= 'http://www.baidu.com'
browser.get(first_url)
time.sleep(2)
#访问新闻页面
second_url='http://news.baidu.com'
browser.get(second_url)
time.sleep(2)
#返回(后退)到百度首页
browser.back()
time.sleep(1)
#前进到新闻页
browser.forward()
time.sleep(2)
browser.quit()

4. Control the browser scroll bar

#coding=utf-8
from selenium import webdriver
import time
#访问百度
driver=webdriver.Chrome()
driver.get("http://www.baidu.com")
#搜索
driver.find_element_by_id("kw").send_keys("selenium")
driver.find_element_by_id("su").click()
time.sleep(3)
#将页面滚动条拖到底部
js="var q=document.documentElement.scrollTop=10000"
driver.execute_script(js)
time.sleep(3)
#将滚动条移动到页面的顶部
js="var q=document.documentElement.scrollTop=0"
driver.execute_script(js)
time.sleep(3)
driver.quit()

5. Keyboard events

1. Usage of keyboard keys

#coding=utf-8
from selenium import webdriver
from selenium.webdriver.common.keys import Keys #需要引入keys 包
import os,time
driver = webdriver.Chrome()
driver.get("http://demo.zentao.net/user-login-Lw==.html")
time.sleep(3)
driver.maximize_window() # 浏览器全屏显示
driver.find_element_by_id("account").clear()
time.sleep(3)
driver.find_element_by_id("account").send_keys("demo")
time.sleep(3)
#tab 的定位相当于清除了密码框的默认提示信息,等同上面的clear()
driver.find_element_by_id("account").send_keys(Keys.TAB)
time.sleep(3)
#通过定位密码框,enter(回车)来代替登陆按钮
driver.find_element_by_name("password").send_keys(Keys.ENTER)
'''
#也可定位登陆按钮,通过enter(回车)代替click()
driver.find_element_by_id("login").send_keys(Keys.ENTER)
'''
time.sleep(3)
driver.quit()

To call keyboard key operations, you need to introduce the keys package: from selenium.webdriver.common.keys import Keys

Call keys through send_keys(): send_keys(Keys.TAB) # TAB send_keys(Keys.ENTER) # Enter

2. Usage of keyboard key combinations

#coding=utf-8
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
import time
driver = webdriver.Chrome()
driver.get("http://www.baidu.com")
#输入框输入内容
driver.find_element_by_id("kw").send_keys("selenium")
time.sleep(3)
#ctrl+a 全选输入框内容
driver.find_element_by_id("kw").send_keys(Keys.CONTROL,'a')
time.sleep(3)
#ctrl+x 剪切输入框内容
driver.find_element_by_id("kw").send_keys(Keys.CONTROL,'x')
time.sleep(3)
#输入框重新输入内容,搜索
driver.find_element_by_id("kw").send_keys("webdriver")
driver.find_element_by_id("su").click()
time.sleep(3)
driver.quit()

6. Mouse events

ActionChains class

context_click() right click

double_click() double click

drag_and_drop() drag

move_to_element() move

1. Position a group of elements

<html>
<head>
<meta http-equiv="content-type" content="text/html;charset=utf-8" />
<title>Checkbox</title>
</head>
<body>
<h3>checkbox</h3>
<div class="well">
<form class="form-horizontal">
<div class="control-group">
<label class="control-label" for="c1">checkbox1</label>
<div class="controls">
<input type="checkbox" id="c1" />
</div>
</div>
<div class="control-group">
<label class="control-label" for="c2">checkbox2</label>
<div class="controls">
<input type="checkbox" id="c2" />
</div>
</div>
<div class="control-group">
<label class="control-label" for="c3">checkbox3</label>
<div class="controls">
<input type="checkbox" id="c3" />
</div>
</div>
<div class="control-group">
<label class="control-label" for="r">radio</label>
<div class="controls">
<input type="radio" id="r1" />
</div>
</div>
<div class="control-group">
<label class="control-label" for="r">radio</label>
<div class="controls">
<input type="radio" id="r2" />
</div>
</div>
</form>
</div>
</body>
</html>
#coding=utf-8
from selenium import webdriver
import time
import os
dr = webdriver.Chrome()
file_path = 'file://' + os.path.abspath('D:\senlenium\htnl\selenium2html\checkbox.html')
dr.get(file_path)
# 选择页面上所有的input,然后从中过滤出所有的checkbox 并勾选之
inputs = dr.find_elements_by_tag_name('input')
for input in inputs:
 if input.get_attribute('type') == 'checkbox':
     input.click()
time.sleep(10)
dr.quit()

 When we open this page through the browser, we see three check boxes and two radio buttons. Position these three checkboxes.

2. Multi-layer frame/window positioning

<html>
<head>
<meta http-equiv="content-type" content="text/html;charset=utf-8" />
<title>frame</title>
<link
href="http://netdna.bootstrapcdn.com/twitter-bootstrap/2.3.2/css/bootstra
p-combined.min.css" rel="stylesheet" />
<script type="text/javascript">$(document).ready(function(){
});
</script>
</head>
<body>
<div class="row-fluid">
<div class="span10 well">
<h3>frame</h3>
<iframe id="f1" src="inner.html" width="800",
height="600"></iframe>
</div>
</div>
</body>
<script
src="http://netdna.bootstrapcdn.com/twitter-bootstrap/2.3.2/js/bootstrap.
min.js"></script>
</html>
<html>
<head>
<meta http-equiv="content-type" content="text/html;charset=utf-8" />
<title>inner</title>
</head>
<body>
<div class="row-fluid">
<div class="span6 well">
<h3>inner</h3>
<iframe id="f2" src="http://www.baidu.com"
width="700"height="500"></iframe>
<a href="javascript:alert('watir-webdriver better than
selenium webdriver;')">click</a>
</div>
</div>
</body>
</html>
#coding=utf-8
from selenium import webdriver
import time
import os
browser = webdriver.Chrome()
file_path = 'file:///' + os.path.abspath('D:\senlenium\htnl\selenium2html\frame.html')
browser.get(file_path)
browser.implicitly_wait(30)
#先找到到ifrome1(id = f1)
browser.switch_to_frame("f1")
#再找到其下面的ifrome2(id =f2)
browser.switch_to_frame("f2")
#下面就可以正常的操作元素了
browser.find_element_by_id("kw").send_keys("D:\senlenium\htnl\selenium2html\selenium")
browser.find_element_by_id("su").click()
time.sleep(3)
browser.quit()

3. Hierarchical positioning

<html>
    <head>
    <meta http-equiv="content-type" content="text/html;charset=utf-8" />
    <title>Level Locate</title>
	<script type="text/javascript" src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
    <link
    href="http://netdna.bootstrapcdn.com/twitter-bootstrap/2.3.2/css/bootstrap-combined.min.css" rel="stylesheet" />
    </head>
    <body>
    <h3>Level locate</h3>
    <div class="span3">
    <div class="well">
    <div class="dropdown">
    <a class="dropdown-toggle" data-toggle="dropdown"
    href="#">Link1</a>
    <ul class="dropdown-menu" role="menu"
    aria-labelledby="dLabel" id="dropdown1" >
    <li><a tabindex="-1" href="#">Action</a></li>
    <li><a tabindex="-1" href="#">Another action</a></li>
    <li><a tabindex="-1" href="#">Something else here</a></li>
    <li class="divider"></li>
    <li><a tabindex="-1" href="#">Separated link</a></li>
    </ul>
    </div>
    </div>
    </div>
    <div class="span3">
    <div class="well">
    <div class="dropdown">
    <a class="dropdown-toggle" data-toggle="dropdown"
    href="#">Link2</a>
    <ul class="dropdown-menu" role="menu"
    aria-labelledby="dLabel" >
    <li><a tabindex="-1" href="#">Action</a></li>
    <li><a tabindex="-1" href="#">Another action</a></li>
    <li><a tabindex="-1" href="#">Something else here</a></li>
    <li class="divider"></li>
    <li><a tabindex="-1" href="#">Separated link</a></li>
    </ul>
    </div>
    </div>
    </div>
    </body>
    <script
    src="http://netdna.bootstrapcdn.com/twitter-bootstrap/2.3.2/js/bootstrap.min.js"></script>
</html>
#coding=utf-8
from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
import time
import os
dr = webdriver.Chrome()
file_path = 'file:///' + os.path.abspath('D:\senlenium\htnl\selenium2html\level_locate.html')
dr.get(file_path)
#点击Link1链接(弹出下拉列表)
dr.find_element_by_link_text('Link1').click()
#找到id 为dropdown1的父元素
WebDriverWait(dr,10).until(lambda the_driver:
the_driver.find_element_by_id('dropdown1').is_displayed())
#在父亲元件下找到link 为Action 的子元素
menu = dr.find_element_by_id('dropdown1').find_element_by_link_text('Action')
#鼠标定位到子元素上
webdriver.ActionChains(dr).move_to_element(menu).perform()
time.sleep(2)
dr.quit()

4. Drop-down box processing

<html>
<body>
<select id="ShippingMethod"
onchange="updateShipping(options[selectedIndex]);" name="ShippingMethod">
<option value="12.51">UPS Next Day Air ==> $12.51</option>
<option value="11.61">UPS Next Day Air Saver ==> $11.61</option>
<option value="10.69">UPS 3 Day Select ==> $10.69</option>
<option value="9.03">UPS 2nd Day Air ==> $9.03</option>
<option value="8.34">UPS Ground ==> $8.34</option>
<option value="9.25">USPS Priority Mail Insured ==> $9.25</option>
<option value="7.45">USPS Priority Mail ==> $7.45</option>
<option value="3.20" selected="">USPS First Class ==> $3.20</option>
</select>
</body>
</html>
#coding=utf-8
from selenium import webdriver
import os,time
driver= webdriver.Chrome()
file_path = 'file:///' + os.path.abspath('D:\senlenium\htnl\selenium2html\drop_down.html')
driver.get(file_path)
time.sleep(2)
#先定位到下拉框
m=driver.find_element_by_id("ShippingMethod")
#再点击下拉框下的选项
m.find_element_by_xpath("//option[@value='10.69']").click()
time.sleep(3)
driver.quit()

5. Processing of alert, confirm and prompt

text returns the text information in alert/confirm/prompt

accept click the confirm button

dismiss click the cancel button, if there is one

send_keys input value. This alert\confirm cannot be used without a dialog box, otherwise an error will be reported.

<html> 
<head> 
<meta http-equiv="content-type" content="text/html;charset=utf-8" />
<title>alert</title> 
<script type="text/javascript" src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<link href="http://netdna.bootstrapcdn.com/twitter-bootstrap/2.3.2/css/bootstrap-combined.min.css" rel="stylesheet" />
<script type="text/javascript"> $(document).ready(function(){ $('#tooltip').tooltip({"placement": "right"}); $('#tooltip').click(function(){ alert('hello,Java12&&Java11!') }); }); </script>
</head> 
<body> 
<div class="row-fluid"> 
<div class="span6 well"> 
<h3>alert</h3> 
<a id="tooltip" href="#" data-toggle="tooltip" title="hello,Java12&&Java11 !">hover to see tooltip</a> 
</div> 
</div> 
</body> 
<script src="http://netdna.bootstrapcdn.com/twitter-bootstrap/2.3.2/js/bootstrap.min.js"></script>
</html>
from selenium import webdriver
from time import sleep
import os
dr = webdriver.Chrome()
file_path = 'file:///' + os.path.abspath('D:\senlenium\htnl\selenium2html\alert.html')
dr.get(file_path)
# 点击链接弹出alert
dr.find_element_by_id('tooltip').click()
sleep(2)
alert = dr.switch_to_alert()
alert.accept()
sleep(2)
dr.quit()

6. Enter the value

<html>
<head>
<meta charset="UTF-8">
<title></title>
<script type="text/javascript">
function disp_prompt(){
var name=prompt("Please enter yourname","")
if (name!=null &&name!=""){
document.write("Hello " +name + "!")
}
}
</script>
</head>
<body>
<input type="button" onclick="disp_prompt()"
value="请点击"/>
</body>
</html>
from selenium import webdriver
from time import sleep
import os
driver=webdriver.Chrome()
driver.implicitly_wait(30)
file_path = 'file:///' + os.path.abspath('D:\\senlenium\\htnl\\selenium2html\\send.html')
driver.get(file_path)
#点击“请点击”
driver.find_element_by_xpath("html/body/input").click()
#输入内容
driver.switch_to_alert().send_keys('webdriver')
driver.switch_to_alert().accept()
sleep(5)
driver.quit()

Guess you like

Origin blog.csdn.net/qq_50156012/article/details/124667707