当前位置:网站首页>Automated testing selenium foundation -- webdriverapi
Automated testing selenium foundation -- webdriverapi
2022-07-04 05:01:00 【Big Balu who likes to knock code】
Preface
After reading this article, you can harvest god horse ? You can let the computer automatically complete a series of things you want to do , such as : Search the browser for some knowledge you want to know , Go online to find a song you want to listen to , you 're right , You don't have to operate it , It can be done by itself .
Catalog
【2】tag name and class name location
【3】link text and partial link text location
(2) An implicit wait ( Intelligent waiting )
【6】 The operation of the browser
【9】 Positioning of complex elements
(2) Multilayer frame positioning
【10】 Handling of special cases
(1)alert Handling of pop-up frames
【1】 A simple automated script
Open Google browser , Enter Baidu search page to search for keywords “ Nanshan south ”, Finally, exit the browser .
# coding = utf-8
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(" Nanshan south ")
time.sleep(3)
browser.find_element_by_id("su").click()
browser.quit()
Script parsing :
- coding=utf-8: Set the encoding format , Prevent confusion code , Editor default utf-8, No need to set ;
- from selenium import webdriver: Import webdriver tool kit , In this way, relevant API;
- browser=webdriver.Chrome(): Get the driver of the controlled browser , Here for Chrome browser , You can also get other browsers , The corresponding browser driver must be installed ;
- browser.find_element_by_id("kw").send_keys(" Nanshan south "): By element id Locate the element you want to operate , And input the corresponding text content ;
- browser.find_element_by_id("su").click(): adopt id Navigate to element , And click ;
- browser.quit(): Exit and close the window .
quit() and close() The difference between :
- colse() Just close the window of the current browser ;
- quit() Method not only closes the window , And I'm going to quit completely webdriver, Release and driverserver Connection between .
【2】 Positioning of elements
Object positioning is the core of automated testing , Want to manipulate an object , First, you need to identify this object , We can go through id Wait for attributes to find elements , The uniqueness of this attribute on the page must be guaranteed . There are several common object location methods :
- id
- name
- classname
- link text
- partial link text
- tag name
- xpath
- css selector
【1】id location
id Is the attribute of the page element ,, Is the most commonly used method of element location , But not all elements have id. Generally, it can be used id To uniquely locate this element .
Such as , adopt Chrome Browser's F12, You can find the attribute information of Baidu input box :
<input id="kw" name="wd" class="s_ipt" value=" Baidu " maxlength="255" autocomplete="off">
【2】tag name and class name location
From the attribute information above , You can see , Not just id and name attribute , It's up to you class and tagname( Tag name ):
- input The label can go through find_element_by_tag_name("input") Function to locate ;;
- class="s_ipt" Can pass find_element_by_class_name("s_ipt") Function positioning Baidu input box ..
We need to pay attention to , Not all elements can be located in these two ways , You must ensure that these two attributes of the element are unique on the page .
【3】link text and partial link text location
- link text: Locate a text link , You can locate it by the content of the link , Of course, the linked content must be unique on the current page ;
- partial link text: Locate by partial connection , You can match only part of the text of the link .
【4】css selector location
Can pass css The selector in locates the elements of the page .
adopt cee Of id Selector to locate the element :
browser.find_element_by_css_selector("#kw").send_keys(" Joker Xue ")
browser.find_element_by_css_selector("#su").click()
【5】XPath location
You can locate any element in the page .
Fetch element XPath:
First, right-click the element to enter the inspection page
【3】 Operate the test object
After positioning to the element , You need to operate on the positioned element .webdriver Common methods of manipulating objects in :
- click: Click on the object ;
- send_keys: Simulate key input on an object
- clear: Clear the text content of the object input ;
- submit: Submit Form ;
- text: Used to get the text information of the element .
【4】 Add wait
(1)sleep wait for
Attract people time package , call sleep Method to make it sleep for a fixed period of time .
from selenium import webdriver
import time
browser = webdriver.Chrome()
browser.get("http://www.baidu.com")
time.sleep(2)
browser.find_element_by_css_selector("#kw").send_keys(" Joker Xue ")
browser.find_element_by_css_selector("#su").click()
# Search Jacky Xue , wait for 5 Seconds later, click Baidu Encyclopedia
time.sleep(5)
browser.find_element_by_link_text(" Baidu Encyclopedia ").click()
time.sleep(5)
browser.quit()
【 We need to pay attention to 】
The above code , If you remove this fixed sleep time , There will be the following mistakes :
Link text not found “ Baidu Encyclopedia ”, Because the search page has not been loaded after clicking , Cannot locate element .
(2) An implicit wait ( Intelligent waiting )
We found that , If you set sleep Wait for , It may take a lot of time , So you can add implicitly_wait(time) Method can easily realize intelligent waiting . Choose a time range to wait intelligently .
【 working principle 】
Implicit waiting is not a fixed waiting time . When the script executes the positioning of an element , If the element can be positioned , Then continue ; If the element cannot be located , Then it continuously determines whether the element is located in the way of polling , Until the set duration is exceeded .
【5】 Information printing
Print page title and url:
from selenium import webdriver
import time
browser = webdriver.Chrome()
browser.get("http://www.baidu.com")
title=browser.title
print(title)
url=browser.current_url
print(url)
【6】 The operation of the browser
- Browser maximization : Invoking the launched browser is not full screen , Sometimes it will affect us to watch the script run , Use maximize_window() Method to maximize the window ;
- Set the width and height of the browser :set_window_size(width,high)
- Operate the browser forward and backward :
【1】 Forward :forward()
【2】 back off :back()- Control the browser scroll bar : The control of the scroll bar of the browser depends on js Script
【1】 Slide the browser scroll bar to the top :【2】 Slide the browser scroll bar to the bottom :# The distance from the top is set to zero driver.documentElement.scrollTop=0
js="var q=document.documentElement.scrollTop=10000" # excute_script() In the current window / The framework executes synchronously js driver.excute_script(js)
【7】 Keyboard events
【1】 Keyboard keys
All keyboard operations , It must be based on positioning to elements ( Element based operations ). Use the keyboard keys , Need to introduce keys package :
from selenium.webdriver.common.keys import Keys
adopt send_keys() Method call key :
send_keys(Keys.TAB) # TAB
send_keys(Keys.ENTER) # enter
send_keys(Keys.SPACE) # Space bar
send_keys(Keys.ESCAPE) # backspace key (Esc)
【2】 Keyboard combination
send_keys(Keys.CONTROL,'a') # Future generations (Ctrl+A)
send_keys(Keys.CONTROL,'c') # Copy (Ctrl+C)
send_keys(Keys.CONTROL,'x') # Clip (Ctrl+X)
send_keys(Keys.CONTROL,'v') # Paste (Ctrl+V)
【8】 Mouse events
Need to import toolkit ActionChains:
from selenium.webdriver.common.action_chains import ActionChains
ActionChains class
Method name | explain |
context_click() | Right mouse click |
double_ click() | double-click |
drag_and_drop() | Drag the |
move_to_element() | Move |
【9】 Positioning of complex elements
(1) Locate a set of elements
webdriver It's easy to use findElement Method to locate a specific object , But sometimes we need to locate a group of objects , Need to use findElements Method :
- Batch operation objects , Put all on the page checkbox All hooked
- Get a set of elements first , Then filter out some objects that need to be located in this group of objects .
example : Check all on the page checkbox
from selenium import webdriver
import time
import os
driver=webdriver.Chrome()
# html File path
path='file:///'+os.path.abspath('C:\\Users\\Lenovo\\Desktop\\selenium2html\\checkbox.html')
driver.get(path)
# Select all on the page input. Then filter out checkbox And check the
checkboxs=driver.find_elements_by_tag_name('input')
for checkbox in checkboxs:
if checkbox.get_attribute('type')=='checkbox':
checkbox.click()
time.sleep(5)
driver.quit()
(2) Multilayer frame positioning
Solve the positioning of page elements on different layer frames :
- If you want to locate elements in a hierarchical framework , You must jump to this framework level first , Before positioning ;
- If you want to locate a certain level , You must jump from the default page .
- Navigate to a level :switch_to.frame(id) adopt frame Of id And other attributes to locate the framework , Switch the currently positioned subject to frame in ;
- switch_to.default_content(): from frame Jump out of the page embedded in , Jump back to the outermost default page .
(3) Hierarchical positioning
Sometimes the elements we need to locate are not directly displayed on the page , You need to perform a series of operations on the page elements before they are displayed , At this time, we need to position layer by layer .( Operate through mouse events )
example : Open local html, Click on link1 Then navigate to one of the columns to highlight it .
from selenium import webdriver
from selenium.webdriver.common.action_chains import ActionChains
import time
import os
driver = webdriver.Chrome()
path = 'file:///'+os.path.abspath('C:\\Users\\Lenovo\\Desktop\\selenium2html\\level_locate.html')
driver.get(path)
# Locate the link1, Click on
driver.find_element_by_link_text('Link1').click()
driver.implicitly_wait(5)
# location Something else here
element = driver.find_element_by_link_text('Something else here')
# Move the mouse to Something else here , Highlight
ActionChains(driver).move_to_element(element).perform()
time.sleep(4)
driver.quit()
(4) Drop down box positioning
For general elements , We only need to position once , But the contents of the drop-down box need to be positioned twice , First navigate to the drop-down box and operate on the drop-down box , Options in the navigate to drop-down box :
- Use it directly xpath To locate
- First locate a group of elements , Then filter according to the attributes of the element , Then carry out the specific operation ;
- First locate a group of elements , Then locate by array subscript
example : Select a specified option in the drop-down box .
driver=webdriver.Chrome()
path='file:///'+os.path.abspath('C:\\Users\\Lenovo\\Desktop\\selenium2html\\drop_down.html')
driver.get(path)
time.sleep(2)
# Go to the drop-down box
driver.find_element_by_id('ShippingMethod').click()
time.sleep(2)
# Navigate to... According to the options in the drop-down box value The value is equal to 8.34 The option to
elements=driver.find_elements_by_tag_name('option')
for element in elements:
if element.get_attribute('value')=='8.34':
element.click()
time.sleep(4)
driver.quit()
【10】 Handling of special cases
(1)alert Handling of pop-up frames
- Locate the pop-up box / Get the operation handle of the pop-up box :switch_to.alert;
- Close the pop box :accept();
- alert Input information in the pop-up box :send_keys()
example : Navigate to the click button , Jump out of the bullet box , Enter the content in the pop-up box , Close the pop box
from selenium import webdriver
import time
import os
driver=webdriver.Chrome()
path='file:///'+os.path.abspath('C:\\Users\\Lenovo\\Desktop\\selenium2html\\send.html')
driver.get(path)
# Positioning elements , Click on , A pop-up box appears
driver.find_element_by_tag_name("input").click()
time.sleep(4)
# Locate the pop-up box
alert=driver.switch_to.alert
# Enter information in the pop-up box
alert.send_keys(" Big bald ")
time.sleep(2)
# Close the pop box
alert.accept()
time.sleep(5)
driver.quit()
(2)div Block processing
If there are many elements on the page , When you cannot accurately locate this element by using its attributes , We can locate the element first div block , Then locate this element .
- First of all, I'll go to div modular ;
- Then go to find the elements that need to be located accurately .
(3) Upload files
Uploading files usually requires opening a local window , Select local file add from the window . We need to consider how to add uploaded files : Navigate to the upload button , adopt send_keys Just add the local file path .( Both absolute and relative paths are OK )
Why can't some page elements of third-party websites be located ?
For security reasons , Prevent some people from using automated scripts to crack passwords . Every time you open a web page, the elements in the web page id Properties will be different , Cannot operate with automated scripts .
边栏推荐
- [matlab] matlab simulates digital baseband transmission system eye diagram of bipolar baseband signal (cosine roll off forming pulse)
- Correct the classpath of your application so that it contains a single, compatible version of com.go
- 【MATLAB】MATLAB 仿真数字基带传输系统 — 数字基带传输系统
- Annex 2-2 confidentiality commitment docx
- 全国职业院校技能大赛(中职组)网络安全竞赛试题—解析
- [go] database framework Gorm
- RPC - grpc simple demo - learn / practice
- Zhongke panyun-2022 Guangdong Trojan horse information acquisition and analysis
- NTFS security permissions
- Useful plug-ins for vscode
猜你喜欢
【QT】定时器
附件六:防守工作简报.docx
Definition of DCDC power supply current
Trie数-字典树
Zhongke Panyun - module a infrastructure setting and safety reinforcement scoring standard
RPC - grpc simple demo - learn / practice
Headache delayed double deletion
中職組網絡安全—內存取證
A summary of the 8544 problem that SolidWorks Standard cannot obtain a license
Annexe VI: exposé sur les travaux de défense. Docx
随机推荐
附件一:202x年xxx攻防演习授权委托书
Capturing and sorting out external Fiddler -- Conversation bar and filter
NTFS 安全权限
红队视角下的防御体系突破之第二篇案例分析
【MATLAB】MATLAB 仿真模拟调制系统 — SSB 系统
【MATLAB】MATLAB 仿真模拟调制系统 — VSB 系统
[matlab] matlab simulates digital baseband transmission system - digital baseband transmission system
When using flash to store parameters, the code area of flash is erased, which leads to the interrupt of entering hardware error
laravel 中获取刚刚插入的记录的id
Solve the problem of failed to load property source from location 'classpathapplication YML 'problem
全国职业院校技能大赛(中职组)网络安全竞赛试题—解析
[matlab] matlab simulation of modulation system - power spectrum and coherent demodulation of AM modulated signal
【MATLAB】通信信号调制通用函数 — 低通滤波器
加密和解密
【MATLAB】MATLAB 仿真数字带通传输系统 — ASK、 PSK、 FSK 系统
RPC - gRPC简单的demo - 学习/实践
Use units of measure in your code for a better life
电子元器件商城与数据手册下载网站汇总
如何构建属于自己的知识引擎?社群开放申请
Introduction and application of rampax in unity: optimization of dissolution effect