当前位置:网站首页>Automatic testing of Web UI: Selenium syntax explanation is the most complete in the history
Automatic testing of Web UI: Selenium syntax explanation is the most complete in the history
2022-07-27 19:07:00 【Test kid】
selenium It's mainly used for automated testing , Support multiple browsers , Crawler is mainly used to solve the problem JavaScript Rendering problems . Simulate the browser to load the web page
One 、 Declare browser objects
Pay attention to point one ,Python The file name or package name should not be named selenium, Will result in failure to import from selenium import webdriver
#webdriver Think of it as a browser drive , To drive a browser, you have to use webdriver, Support multiple browsers , Here we use Chrome For example
browser = webdriver.Chrome()Two 、 Visit the page and get the page html
from selenium import webdriver
browser = webdriver.Chrome()
browser.get('https://www.taobao.com')
print(browser.page_source)#browser.page_source Is to get all the pages html
browser.close()3、 ... and 、 Look for the element
Single element
from selenium import webdriver
browser = webdriver.Chrome()
browser.get('https://www.taobao.com')
input_first = browser.find_element_by_id('q')
input_second = browser.find_element_by_css_selector('#q')
input_third = browser.find_element_by_xpath('//*[@id="q"]')
print(input_first,input_second,input_third)
browser.close()Common search methods
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_selectorYou can also use general methods
from selenium import webdriver
from selenium.webdriver.common.by import By
browser = webdriver.Chrome()
browser.get('https://www.taobao.com')
input_first = browser.find_element(BY.ID,'q')# The first parameter passes in the name , The second is to pass in specific parameters
print(input_first)
browser.close()
Multiple elements ,elements Multiple s
input_first = browser.find_elements_by_id('q')Four 、 Element interaction - Search box to enter keywords for automatic search
from selenium import webdriver
import time
browser = webdriver.Chrome()
browser.get('https://www.taobao.com')
input = browser.find_element_by_id('q')# Find the search box
input.send_keys('iPhone')# Send in keywords
time.sleep(5)
input.clear()# Clear the search box
input.send_keys(' Men's underwear ')
button = browser.find_element_by_class_name('btn-search')# Find the search button
button.click()More operations :
http://selenium-python.readthedocs.io/api.html#module-selenium.webdriver.remote.webelement
# It can have attributes 、 Screenshots, etc 5、 ... and 、 Interactive action , Drive the browser to move , Simulate drag action , To attach an action to an action chain for serial execution
from selenium import webdriver
from selenium.webdriver import ActionChains # Introduce the action chain browser = webdriver.Chrome()
url = 'http://www.runoob.com/try/try.php?filename=jqueryui-api-droppable'
browser.get(url)
browser.switch_to.frame('iframeResult')# Switch to iframeResult frame
source = browser.find_element_by_css_selector('#draggable')# Find the dragged object
target = browser.find_element_by_css_selector('#droppable')# Find the target
actions = ActionChains(browser)# Statement actions object
actions.drag_and_drop(source, target)
actions.perform()# Executive action
More operations :
http://selenium-python.readthedocs.io/api.html#module-selenium.webdriver.common.action_chains6、 ... and 、 perform JavaScript
Some actions may not provide api, Such as progress bar drop-down , At this time , We can execute... Through code JavaScript
from selenium import webdriver
browser = webdriver.Chrome()
browser.get('https://www.zhihu.com/explore')
browser.execute_script('window.scrollTo(0, document.body.scrollHeight)')
browser.execute_script('alert("To Bottom")')7、 ... and 、 Get element information
get attribute
from selenium import webdriver
from selenium.webdriver import ActionChains
browser = webdriver.Chrome()
url = 'https://www.zhihu.com/explore'
browser.get(url)
logo = browser.find_element_by_id('zh-top-link-logo')# Get website logo
print(logo)
print(logo.get_attribute('class'))
browser.close()Get the text value
from selenium import webdriver
browser = webdriver.Chrome()
url = 'https://www.zhihu.com/explore'
browser.get(url)
input = browser.find_element_by_class_name('zu-top-add-question')
print(input.text)#input.text Text value
browser.close()# obtain Id, Location , Tag name , size
from selenium import webdriver
browser = webdriver.Chrome()
url = 'https://www.zhihu.com/explore'
browser.get(url)
input = browser.find_element_by_class_name('zu-top-add-question')
print(input.id)# obtain id
print(input.location)# To obtain position
print(input.tag_name)# Get the tag name
print(input.size)# Get size
browser.close()8、 ... and 、Frame operation
frame Equivalent to a separate web page , If in the parent network frame Find subclasses , You must switch to the of the subclass frame, If a subclass finds a parent class, it also needs to switch first
from selenium import webdriver
from selenium.common.exceptions import NoSuchElementException
browser = webdriver.Chrome()
url = 'http://www.runoob.com/try/try.php?filename=jqueryui-api-droppable'
browser.get(url)
browser.switch_to.frame('iframeResult')
source = browser.find_element_by_css_selector('#draggable')
print(source)
try:
logo = browser.find_element_by_class_name('logo')
except NoSuchElementException:
print('NO LOGO')
browser.switch_to.parent_frame()
logo = browser.find_element_by_class_name('logo')
print(logo)
print(logo.text)Nine 、 wait for
An implicit wait
When you use implicit wait for tests to execute , If WebDriver Not in the DOM Elements found in , Will continue to wait , After the set time is exceeded, the exception that the element cannot be found is thrown .
let me put it another way , When the search element or element does not appear immediately , Implicit wait will wait a while to find DOM, The default time is 0
from selenium import webdriver
browser = webdriver.Chrome()
browser.implicitly_wait(10)
# Wait for ten seconds, and if it cannot be loaded, an exception will be thrown ,10 It is loaded within seconds and returns normally
browser.get('https://www.zhihu.com/explore')
input = browser.find_element_by_class_name('zu-top-add-question')
print(input)Explicit waiting
Specify a wait condition , And a maximum waiting time , The program will determine whether the conditions are met within the waiting time , Return if satisfied , If you are not satisfied, you will continue to wait , An exception will be thrown after time
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
browser = webdriver.Chrome()
browser.get('https://www.taobao.com/')
wait = WebDriverWait(browser, 10)
input = wait.until(EC.presence_of_element_located((By.ID, 'q')))
button = wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR, '.btn-search')))
print(input, button)title_is The title is something
title_contains The title contains something
presence_of_element_located Elements load out , Incoming location tuples , Such as (By.ID, 'p')
visibility_of_element_located The element is visible , Incoming location tuples
visibility_of so , Pass in the element object
presence_of_all_elements_located All elements load out
text_to_be_present_in_element An element text contains some text
text_to_be_present_in_element_value An element value contains some text
frame_to_be_available_and_switch_to_it frame Load and switch
invisibility_of_element_located Elements are not visible
element_to_be_clickable Elements can be clicked
staleness_of Determine if an element is still DOM, Can determine whether the page has been refreshed
element_to_be_selected The elements are optional , Pass element object
element_located_to_be_selected The elements are optional , Incoming location tuples
element_selection_state_to_be Pass in the element object and state , Equal return True, Otherwise return to False
element_located_selection_state_to_be Incoming location tuples and status , Equal return True, Otherwise return to False
alert_is_present Does it appear? Alert
The detailed content :
http://selenium-python.readthedocs.io/api.html#module-selenium.webdriver.support.expected_Ten 、 Forward and backward - Implement the forward and backward of the browser to browse different web pages
import time
from selenium import webdriver
browser = webdriver.Chrome()
browser.get('https://www.baidu.com/')
browser.get('https://www.taobao.com/')
browser.get('https://www.python.org/')
browser.back()
time.sleep(1)
browser.forward()
browser.close()11、 ... and 、Cookies
from selenium import webdriver
browser = webdriver.Chrome()
browser.get('https://www.zhihu.com/explore')
print(browser.get_cookies())
browser.add_cookie({'name': 'name', 'domain': 'www.zhihu.com', 'value': 'germey'})
print(browser.get_cookies())
browser.delete_all_cookies()
print(browser.get_cookies())Tab Management Add browser window
import time
from selenium import webdriver
browser = webdriver.Chrome()
browser.get('https://www.baidu.com')
browser.execute_script('window.open()')
print(browser.window_handles)
browser.switch_to_window(browser.window_handles[1])
browser.get('https://www.taobao.com')
time.sleep(1)
browser.switch_to_window(browser.window_handles[0])
browser.get('http://www.fishc.com')Twelve 、 exception handling
from selenium import webdriver
browser = webdriver.Chrome()
browser.get('https://www.baidu.com')
browser.find_element_by_id('hello')
from selenium import webdriver
from selenium.common.exceptions import TimeoutException, NoSuchElementException
browser = webdriver.Chrome()
try:
browser.get('https://www.baidu.com')
except TimeoutException:
print('Time Out')
try:
browser.find_element_by_id('hello')
except NoSuchElementException:
print('No Element')
finally:
browser.close()
# Detailed documentation :
http://selenium-python.readthedocs.io/api.html#module-selenium.common.exceptionsFinally, I also sorted out some software testing learning materials , It should be very helpful for small partners learning software testing , In order to better organize each module
Need my keywords for private messages 【555】 Get it for free Note that the keywords are :555
Full set of software test automation test teaching video

300G Download tutorial materials 【 Video tutorial +PPT+ Project source code 】

A complete set of software testing automation testing factory has been


边栏推荐
猜你喜欢

NPM basic use

MySQL 04 高级查询(二)

I'm afraid I won't use the JMeter interface testing tool if I accept this practical case

JDBC-MySql 01 JDBC操作MySql(增删改查)

MySQL 01 关系型数据库设计

Bathroom with demister vanity mirror touch chip-dlt8t10s

进行接口测试时,连接数据库,对数据源进行备份、还原、验证操作

Sentinel1.8.4 persistent Nacos configuration

Redis annotation

Household mute mosquito repellent lamp chip-dltap703sd-jericho
随机推荐
MySQL 04 advanced query (II)
Nodejs template engine EJS
C file and folder input / output stream code
IDEA连接数据库时区问题,报红Server returns invalid timezone. Need to set ‘serverTimezone‘ property.
PHP字符串操作
Whole body multifunctional massage instrument chip-dltap602sd
Big enemies, how to correctly choose the intended enterprises in the new testing industry?
WinForm screenshot save C code
Greedy method, matroid and submodular function (refer)
Normal distribution, lognormal distribution, generation of normal random numbers
Full automatic breast pump chip dltap703sd
功率单位(power control)
Using MATLAB to generate graphics for journals and conferences - plot
Dynamic proxy
JMeter interface automation - how to solve the content type conflict of request headers
Docker - docker installation, MySQL installation on docker, and project deployment on docker
阿里云视频点播服务的开通和使用
ref 关键字的用法
How to generate random numbers with standard distribution or Gaussian distribution
Unity显示Kinect捕获的镜头