当前位置:网站首页>[test development] automated test selenium (II) -- common APIs for webdriver
[test development] automated test selenium (II) -- common APIs for webdriver
2022-06-13 03:49:00 【Bryant tapping the code】
【 Test Development 】 automated testing selenium( Two )——webdriver frequently-used API
- A simple script
- Positioning of elements
- Operate the test object
- Add wait
- Print information
- Browser operation
- Keyboard events
- Mouse events
- Locate a set of elements
- Multilayer frame positioning
- Hierarchical positioning
- Drop down box processing
- alert、confirm、prompt To deal with
- DIV Dialog processing
- Upload file operation
A simple script
Positioning of elements
Be careful : Either way , The uniqueness of this attribute on the page must be guaranteed
webdriver Provides a series of object location methods , There are several commonly used
- id
- name
- class name
- link text
- partial link text
- tag name
- xpath
- css selector
for example : A Baidu input box , You can use this way to locate ( Here are html Code
)
<input id="kw" class="s_ipt" type="text" maxlength="100" name="wd" autocomplete="off">
Script code :
#coding=utf-8
from selenium import webdriver
import time
browser = webdriver.Chrome()
browser.get("http://www.baidu.com")
######### Positioning method of Baidu input box ##########
# adopt id Way positioning
browser.find_element_by_id("kw").send_keys("selenium")
# adopt name Way positioning
browser.find_element_by_name("wd").send_keys("selenium")
# adopt tag name Way positioning
browser.find_element_by_tag_name("input").send_keys("selenium") Can't succeed , because input Too many, not the only .
# adopt class name Way positioning
browser.find_element_by_class_name("s_ipt").send_keys("selenium")
# adopt CSS Way positioning
browser.find_element_by_css_selector("#kw").send_keys("selenium")
# adopt xphan Way positioning
browser.find_element_by_xpath("//*[@id='kw']").send_keys("selenium")
############################################
browser.find_element_by_id("su").click()
time.sleep(3)
browser.quit()
id and name location
id and name It is our most commonly used positioning method , Because most controls have these two properties , And in the control id and name When naming, it usually makes sense and takes different names . These two attributes make it quite easy for us to find the attributes on a page .
We use front-end tools , for example chrome Of F12, eureka Attribute information of Baidu input box , as follows :
<input id="kw" class="s_ipt" type="text" maxlength="100" name="wd" autocomplete="off">
id=”kw”
adopt find_element_by_id("kw")
The function is to capture Baidu input box
name=”wd”
adopt find_element_by_name("wd")
Function can also capture Baidu input box
tag name and class name location
From the attribute information of Baidu input box above , We see , Not just id and name Two attributes ,
such as class and tag name( Tag name )
input
Is the name of a label , Can pass find_element_by_tag_name("input")
Function to locate .
class="s_ipt"
, adopt find_element_by_class_name("s_ipt")
Function capture Baidu input box .
CSS location
CSS(Cascading Style Sheets) It's a language , It's used to describe HTML and XML The presentation of the document .
CSS Use selectors to bind properties to page elements . These selectors can be selenium As an alternative positioning strategy .
CSS It is flexible and can select any property of the control , In the example above :find_element_by_css_selector("#kw")
adopt find_element_by_css_selector( ) function , Select Baidu input box id Attribute to define
CSS The acquisition of can be used chrome Of F12 In developer mode Element- Right click -copy-copy selector To get
XPath location
XPath It's a kind of XML The language for locating elements in the document . because HTML Can be seen as XML An implementation of , therefore selenium Users can use this powerful language in web Positioning elements in application .
XPath Extended the above id and name Positioning mode , Offers many possibilities .
XPATH The acquisition of can be used chrome Of F12 In developer mode Element- Right click -copy-copy xpath To get
Such as :find_element_by_xpath("//*[@id='kw']")
link text location
Sometimes it's not an input box or a button , It's a text link , We can go through link
#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()
Partial link text
Positioning through partial links , This is sometimes used , I haven't thought of a good use . Take the example above , I can match only part of the text of the link :
#coding=utf-8
from selenium import webdriver
browser = webdriver.Chrome()
browser.get("http://www.baidu.com")
browser.find_element_by_partial_link_text("hao").click()
browser.quit()
Operate the test object
As mentioned earlier, a lot of knowledge is positioning elements , Positioning is only the first step , After positioning, you need to operate this element . Mouse click or keyboard input , It depends on whether we are positioning the button or the input box .
Generally speaking ,webdriver There are several common methods to manipulate objects in :
- click Click on the object
- send_keys Simulate key input on an object
- clear Clear the contents of the object , If you can
- submit Clear the contents of the object , If you can
- text Used to get the text information of the element
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)
# adopt submit() To operate
driver.find_element_by_id("su").submit()
time.sleep(3)
driver.quit()
send_keys("xx") Used to enter... In an input box xx Content .
click() Used to click a button
clear() Used to clear the contents of the input box , For example, baidu input box has one by default “ Please enter keywords ” Information about
, For another example, our login box generally has “ account number ”“ password ” Such default information ,clear Can help us clear this information .
submit Submit Form
hold “ use Baidu Search ” The operation starts from click Switch to submit Can achieve the same effect :driver.find_element_by_id("su").submit()
text Get element text
text Used to get the text information of the element
#coding=utf-8
from selenium import webdriver
import time
driver = webdriver.Chrome()
driver.get("http://www.baidu.com")
time.sleep(2)
#id = cp Text information for the element
data=driver.find_element_by_id("cp").text
print data # Print information
time.sleep(3)
driver.quit()
Output :
2018 Baidu Read Before Using Baidu Feedback Beijing ICP Prove 030173 Number
Add wait
Adding hibernation is very simple , We need to introduce time package , You can freely add sleep time in the script
import time
time.sleep(3)
Intelligent waiting
By adding implicitly_wait() Method can easily realize intelligent waiting ;implicitly_wait(30) The usage of should be better than time.sleep() More intelligent The latter can only choose a fixed time to wait , The former can wait intelligently within a time range .
# coding = utf-8
from selenium import webdriver
import time # Transfer in time function
browser = webdriver.Chrome()
browser.get("http://www.baidu.com")
browser.implicitly_wait(30) # Intelligent waiting 30 second
browser.find_element_by_id("kw").send_keys("selenium")
browser.find_element_by_id("su").click()
browser.quit()
What the two kinds of waiting have in common :
Enough waiting time , If the element required by the code executed in the next sentence is not loaded , Will throw an exception
Print information
Print tile And url
#coding = utf-8
from selenium import webdriver
driver = webdriver.Chrome()
driver.get('http://www.baidu.com')
print driver.title # Put the page title Print out
print driver.current_url # Print url
driver.quit()
Although I didn't see the execution process of the script , But in the implementation results, I see
This shows that the page is opened correctly
Browser operation
Browser maximization
We know that the browser launched by calling is not full screen , This will not affect the execution of the script , But sometimes it affects us “ watch ” Script execution .
#coding=utf-8
from selenium import webdriver
import time
browser = webdriver.Chrome()
browser.get("http://www.baidu.com")
print " Browser maximization "
browser.maximize_window() # Maximize browser display
time.sleep(2)
browser.find_element_by_id("kw").send_keys("selenium")
browser.find_element_by_id("su").click()
time.sleep(3)
browser.quit()
Set browser width 、 high
Maximization is still not flexible enough , Can you set the width of browsing at will 、 High display ? Of course you can .
#coding=utf-8
from selenium import webdriver
import time
browser = webdriver.Chrome()
browser.get("http://www.baidu.com")
time.sleep(2)
# The parameter numbers are pixels
print " Set browser width 480、 high 800 Show "
browser.set_window_size(480, 800)
time.sleep(3)
browser.quit()
Operate the browser forward 、 back off
There is a back button on the browser 、 Forward button , It is more convenient for people browsing the web ; For doing web since For the students of dynamic test, it should be a difficult problem to simulate ; It's very simple , Let's see below. python How to implement .
back off :back()
Forward :forward()
#coding=utf-8
from selenium import webdriver
import time
browser = webdriver.Chrome()
# Visit Baidu Homepage
first_url= 'http://www.baidu.com'
print "now access %s" %(first_url)
browser.get(first_url)
time.sleep(2)
# Visit the news page
second_url='http://news.baidu.com'
print "now access %s" %(second_url)
browser.get(second_url)
time.sleep(2)
# return ( back off ) To Baidu Homepage
print "back to %s "%(first_url)
# back off
browser.back()
time.sleep(1)
# Go to the news page
print "forward to %s"%(second_url)
# Forward
browser.forward()
time.sleep(2)
browser.quit()
Control the browser scroll bar
#coding=utf-8
from selenium import webdriver
import time
# Visit Baidu
driver=webdriver.Chrome()
driver.get("http://www.baidu.com")
# Search for
driver.find_element_by_id("kw").send_keys("selenium")
driver.find_element_by_id("su").click()
time.sleep(3)
# Drag the page scroll bar to the bottom
js="var q=document.documentElement.scrollTop=10000"
driver.execute_script(js)
time.sleep(3)
# Move the scroll bar to the top of the page
js="var q=document.documentElement.scrollTop=0"
driver.execute_script(js)
time.sleep(3)
driver.quit()
execute_script(script, *args), In the current window / The framework executes synchronously javaScript
Keyboard events
Keyboard key usage
To call the keyboard key operation, you need to introduce keys package :from selenium.webdriver.common.keys import Keys
adopt send_keys() Call the key :
- send_keys(Keys.TAB) # TAB
- send_keys(Keys.ENTER) # enter
#coding=utf-8
from selenium import webdriver
from selenium.webdriver.common.keys import Keys # Need to introduce keys package
import os,time
driver = webdriver.Chrome()
driver.get("http://demo.zentao.net/user-login-Lw==.html")
time.sleep(3)
driver.maximize_window() # Browser full screen display
driver.find_element_by_id("account").clear()
time.sleep(3)
driver.find_element_by_id("account").send_keys("demo")
time.sleep(3)
#tab The positioning of is equivalent to clearing the default prompt of the password box , Equal to the above clear()
driver.find_element_by_id("account").send_keys(Keys.TAB)
time.sleep(3)
# By locating the password box ,enter( enter ) Instead of the login button
driver.find_element_by_name("password").send_keys(Keys.ENTER)
''' # You can also locate the login button , adopt enter( enter ) Instead of click() driver.find_element_by_id("login").send_keys(Keys.ENTER) '''
time.sleep(3)
driver.quit()
Keyboard combination usage
#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")
# Input box input content
driver.find_element_by_id("kw").send_keys("selenium")
time.sleep(3)
#ctrl+a Select all the contents of the input box
driver.find_element_by_id("kw").send_keys(Keys.CONTROL,'a')
time.sleep(3)
#ctrl+x Cut the input box
driver.find_element_by_id("kw").send_keys(Keys.CONTROL,'x')
time.sleep(3)
# Input box to re-enter content , Search for
driver.find_element_by_id("kw").send_keys("webdriver")
driver.find_element_by_id("su").click()
time.sleep(3)
driver.quit()
Mouse events
Need to use ActionChains class
- context_click() Right click
- double_click() double-click
- drag_and_drop() Drag the
- move_to_element() Move
#coding=utf-8
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.action_chains import ActionChains
import time
driver = webdriver.Chrome()
driver.get("http://news.baidu.com")
qqq =driver.find_element_by_xpath(".//*[@id='s_btn_wr']")
ActionChains(driver).context_click(qqq).perform() # Right click
ActionChains(driver).double_click(qqq).perform() # double-click
# Locate the original location of the element
element = driver.find_element_by_id("s_btn_wr")
# Locate the target location to which the element is to be moved
target = driver.find_element_by_class_name("btn")
# Perform the move operation of the element
ActionChains(driver).drag_and_drop(element, target).perform()
ActionChains(driver)
Generate user behavior . All actions are stored in actionchains object . adopt perform() Storage behavior .
move_to_element(menu)
Move the mouse over an element ,menu The above has defined which element he points to
perform()
Perform all stored actions
Locate a set of elements
Locating a set of objects is generally used in the following scenarios :
- Batch operation objects , For example, all the checkbox All hooked
- First get a set of objects , Then filter out some objects that need to be located in this group of objects . For example, locate all the information on the page checkbox, Then choose the last
Here's a prepared html Presentation files
checkbox.html The access document should be placed in a directory with the script
<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>
Through the browser to open this page, we see three check boxes and two radio boxes . Now let's locate these three check boxes .
#coding=utf-8
from selenium import webdriver
import time
import os
dr = webdriver.Chrome()
file_path = 'file:///' + os.path.abspath('checkbox.html')
dr.get(file_path)
# Select all on the page input, Then filter out all checkbox And check
inputs = dr.find_elements_by_tag_name('input')
for input in inputs:
if input.get_attribute('type') == 'checkbox':
input.click()
time.sleep(2)
dr.quit()
get_attribute: Get attribute value .
Multilayer frame positioning
#coding=utf-8
from selenium import webdriver
import time
import os
browser = webdriver.Chrome()
file_path = 'file:///' + os.path.abspath('frame.html')
browser.get(file_path)
browser.implicitly_wait(30)
# Find it first ifrome1(id = f1)
browser.switch_to_frame("f1")
# Then find the... Below it ifrome2(id =f2)
browser.switch_to_frame("f2")
# Now you can operate the elements normally
browser.find_element_by_id("kw").send_keys("selenium")
browser.find_element_by_id("su").click()
time.sleep(3)
browser.quit()
Hierarchical positioning
Positioning ideas :
The specific idea is : First click to display 1 A drop-down menu , Then navigate to the... Where the drop-down menu is located ul, Reposition this ul Under a specific link.
ad locum , We locate the second 1 From a drop-down menu Action This option .
#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('level_locate.html')
dr.get(file_path)
# Click on Link1 link ( Pop up the drop-down list )
dr.find_element_by_link_text('Link1').click()
# find id by dropdown1 Parent element of
WebDriverWait(dr,10).until(lambda the_driver:
the_driver.find_element_by_id('dropdown1').is_displayed())
# Find... Under the father element link by Action Child elements
menu = dr.find_element_by_id('dropdown1').find_element_by_link_text('Action')
# Position the mouse over the child element
webdriver.ActionChains(dr).move_to_element(menu).perform()
time.sleep(2)
dr.quit()
WebDriverWait(dr, 10)
10 Every second 500 Millisecond scan 1 Secondary page changes , Ends when the specified element appears .dr No explanation , Previous operation webdriver.firefox() The handle of
is_displayed()
Whether the element is visible to the user
Drop down box processing
Drop down box is one of the most common page elements , For general elements , We only need to position once , but The contents in the drop-down box need to be Two positioning , Go to the drop-down box first , Then navigate to the options in the drop-down box .
Now let's select... From the drop-down list through the script $10.69
#coding=utf-8
from selenium import webdriver
import os,time
driver= webdriver.Chrome()
file_path = 'file:///' + os.path.abspath('drop_down.html')
driver.get(file_path)
time.sleep(2)
# Go to the drop-down box first
m=driver.find_element_by_id("ShippingMethod")
# Then click the option under the drop-down box
m.find_element_by_xpath("//option[@value='10.69']").click()
time.sleep(3)
driver.quit()
This may be different from the previous operation , First, locate the element of the drop-down box , Then select the option in the drop-down list to click
alert、confirm、prompt To deal with
- text return alert/confirm/prompt Text messages in
- accept Click the confirm button
- dismiss Click the Cancel button , If any
- send_keys The input values , This alert\confirm It doesn't work without dialog boxes , Otherwise, it will report a mistake
Be careful :switch_to_alert() Can only handle native alert
# -*- coding: utf-8 -*-
from selenium import webdriver
from time import sleep
import os
dr = webdriver.Chrome()
file_path = 'file:///' + os.path.abspath('alert.html')
dr.get(file_path)
# Click the link to pop up alert
dr.find_element_by_id('tooltip').click()
sleep(2)
# Navigate to the pop-up box
alert = dr.switch_to_alert()
# Click on the confirmation
alert.accept()
sleep(2)
dr.quit()
example 2
# Accept warning messages
alert = dr.switch_to_alert()
alert.accept()
# Get text information and print
alert = dr.switch_to_alert()
print alert.text
# Cancel the dialog ( If any )
alert = dr.switch_to_alert()
alert.dismiss()
# The input values
alert = dr.switch_to_alert()
alert.send_keys("hello word")
DIV Dialog processing
More often than not, what we encounter in practical applications is not a simple warning box , But a conversation box that provides more functions .
# -*- coding: utf-8 -*-
from selenium import webdriver
from time import sleep
import os
import selenium.webdriver.support.ui as ui
dr = webdriver.Chrome()
file_path = 'file:///' + os.path.abspath('modal.html')
dr.get(file_path)
# Open the dialog box
dr.find_element_by_id('show_modal').click()
sleep(3)
# Click the link in the dialog
link = dr.find_element_by_id('myModal').find_element_by_id('click')
link.click()
#dr.execute_script('$(arguments[0]).click()', link)
sleep(4)
# close dialog boxes
buttons =dr.find_element_by_class_name('modal-footer').find_elements_by_tag_name('button')
buttons[0].click()
sleep(2)
dr.quit()
Upload file operation
File upload operation is also one of the common functions , Upload function does not use new methods or functions , The key is thinking .
In the upload process, a local window is usually opened , Select local file add from the window . therefore , It is usually stuck in how to operate the local window to add uploaded files .
Actually , stay selenium webdriver It's not as complicated as we think Just locate the upload button , adopt send_keys Just add the local file path . Both absolute and relative paths are OK , The key is that the uploaded file exists .
#coding=utf-8
from selenium import webdriver
import os,time
driver = webdriver.Chrome()
# The script should be consistent with upload_file.html Same directory
file_path = 'file:///' + os.path.abspath('upload.html')
driver.get(file_path)
# Locate the upload button , Add local files
driver.find_element_by_name("file").send_keys('D:\\PycharmProjects\\test\\upload.txt')
time.sleep(2)
driver.quit()
边栏推荐
- Synching build your own synchronization cloud
- Lambda termination operation find and match nonematch
- LVS four layer load balancing cluster (6) LVS working mode
- LVS四层负载均衡集群(4)负载均衡的主要方式
- Lambda termination operation find and match anymatch
- Doris data backup and recovery
- 单片机:Modbus 通信协议介绍
- Simulink code generation: table lookup module and its code
- 【测试开发】自动化测试selenium(三)——unittest框架解析
- Field * doesn't have a default value problem
猜你喜欢
Explain usage, field explanations, and optimization instances of MySQL
[test development] blog system - LoadRunner performance test (publish blog function benchmark test)
单片机:红外遥控通信原理
[test development] automatic test selenium (I)
Goframe day 5
LVS four layer load balancing cluster (6) LVS working mode
单片机:RS485 通信与 Modbus 协议
What to bring to 2022
无人机避障四种常见技术中,为何大疆首选双目视觉
Among the four common technologies for UAV obstacle avoidance, why does Dajiang prefer binocular vision
随机推荐
Watering artifact based on Huawei cloud Internet of things (stm32+esp8266)
2022春学期总结
Lambda终结操作count
Serialization & deserialization
Jumpserver: user - system privileged user - Asset - authorization
【Web】Cookie 和 Session
Goframe day 4
Spark optimization - Performance (general performance, operator, shuffle, JVM) tuning
ROS中的msg消息
任总与系统工程领域科学家、专家会谈纪要
LeetCode185. All employees with the top three highest wages in the Department (MySQL)
Simulink code generation: table lookup module and its code
CDN domain name
单片机:Modbus 通信协议介绍
Lambda终结操作查找与匹配allMatch
【MySQL】索引与事务
Determine whether the file encoding format is UTF-8 or GBK
Mobile communication exercises
【测试开发】自动化测试selenium篇(一)
手机私有充电协议解读