selenium4 automated testing

1. Layered automated testing

Traditional automated testing: based on the UI layer, black box -> program or tool to perform
layered automated testing: advocate multi-layer automated testing from UI single layer to black box and white box. Agile master Mike Cohn first proposed the concept of the test pyramid, and on this basis, master Martin Fowler proposed the concept of layered automated testing.

UI automation testing is mainly to implement manual test cases, which can reduce the cost of regression testing. Usually, if the software requirements do not change frequently, the project cycle is long, and the automated test scripts can be reused, it is suitable for automated testing.

Two, selenium introduction

Basic understanding

One of the mainstream Web UI automation testing libraries, it has experienced 4 major versions so far. The content of this article is based on selenium-4.4.3. Selenium consists of some plug-ins and class libraries: selenium IDE (browser recording and playback), selenium Grid (testing on multiple computers or heterogeneous environments), selenium webDriver (client API interface, control browser driver).

appium, (application+selenium) is one of the mainstream automated testing tools on the mobile platform. It encapsulates the standard selenium client class library, provides users with common selenium commands in json format, and additional commands related to mobile device control.

"""一组基础的用例示例,注意v4版本的少数改动,比如定位一个元素现在用find_element(self,by,value),一组就用find_elements"""

from selenium import webdriver
from selenium.webdriver.common.by import By  # 导入By这个类
import time

driver = webdriver.Chrome()  # 创建浏览器对象driver
driver.get("https://cn.bing.com/?mkt=zh-CN")  # 调用get()访问必应中国首页
driver.find_element(By.ID, "sb_form_q").send_keys('python')  # 定位到输入框,并输入“python”
driver.find_element(By.ID, "search_icon").click()  # 定位到搜索图标并点击
time.sleep(3)  # 休息3秒
driver.close()  # 关闭浏览器

WebDriver API

1. Eight methods of element positioning

id、name、class、tag

link(By.LINK_TEXT、By.PARTIAL_LINK_TEXT)

from selenium import webdriver
from selenium.webdriver.common.by import By
import time

driver = webdriver.Chrome()
driver.get("https://www.runoob.com/python3/python3-tutorial.html")
driver.find_element(By.LINK_TEXT, "JAVA").click()  # 通过含herf的元素的文本内容来定位元素“JAVA”
time.sleep(2)
driver.find_element(By.PARTIAL_LINK_TEXT, "简介").click()  # 通过部分文本内容找到“Java 教程”
time.sleep(2)
driver.close()

[External link picture transfer failed, the source site may have an anti-theft link mechanism, it is recommended to save the picture and upload it directly (img-2bFuX9LH-1668346343334) (C:\Users\Maverick\AppData\Roaming\Typora\typora-user-images\ image-20220926145746295.png)]

xpath : XML path locator, generally right-click to copy the path, or write it yourself after mastering the (nodename / // . … @ *) expression

css selector : similar to xpath, copy or write the path yourself after mastering the relevant syntax

2. Common methods in webdriver

from selenium import webdriver
from selenium.webdriver.common.by import By
import time


driver = webdriver.Chrome()
driver.get("http://www.baidu.com")

# 常见的有send_keys(value)、click()、clear()、submit()(提交表单)等等

# 设置浏览器窗口的宽500,高400
driver.set_window_size(500, 400)

# 窗口最大化
driver.maximize_window()

# 获取输入框的尺寸
size = driver.find_element(By.ID, 'kw').size
print(size)

# 获取左下角“关于百度”的文本
text = driver.find_element(By.CLASS_NAME, 'text-color').text
print(text)

# 返回元素的属性值,可以是id、name、type等任意属性
attribute = driver.find_element(By.ID, 'kw').get_attribute('name')
print(attribute)

# 返回的是元素是否可见的值,为True或者False
r = driver.find_element(By.ID, 'kw').is_displayed()
print(r)

time.sleep(3)
driver.close()

3. Mouse operation

'''
webdriver中鼠标操作的相关方法都在ActionChains类中。常用的有:
perform() ——执行ActionChains类中存储的所有行为
context_click() ——右击		double_click() ——双击
drag_and_drop() ——拖动		move_to_element() ——悬停
'''
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver import ActionChains

driver = webdriver.Chrome()
driver.get("https://www.baidu.com")
driver.maximize_window()
e = driver.find_element(By.ID, 's-usersetting-top')  # 找到“设置”按钮
ActionChains(driver).move_to_element(e).perform()  # 执行“鼠标悬停”的动作

4. Keyboard operation

It is usually used less, and it is used in special cases such as when special characters need to be input.

from selenium.webdriver.common.keys import Keys  # 要先导入Keys这个类
from selenium import webdriver
from selenium.webdriver.common.by import By

driver = webdriver.Chrome()
driver.maximize_window()
driver.get("https://www.baidu.com")
e = driver.find_element(By.ID, 'kw')
e.send_keys('python123')
e.send_keys(Keys.BACK_SPACE)  # 删除键
"""
send_keys(Keys.SPACE) ——空格键		send_keys(Keys.TAB) ——制表键
send_keys(Keys.ENTER) ——回车键		send_keys(Keys.ESCAPE) ——回退键
send_keys(Keys.CONTROL,'a') ——Ctrl+a,类似还有Ctrl+c,Ctrl+x,Ctrl+v
send_keys(Keys.F1) ——类似还有F2……F12
"""

5. Obtain verification information

from selenium import webdriver
from selenium.webdriver.common.by import By


driver = webdriver.Chrome()
driver.get('https://www.baidu.com')
print('Before search====================')

def test():
    # 打印当前页面title
    title = driver.title
    print('title:' + title)
	# 打印当前页面的URL
    now_url = driver.current_url
    print('url:' + now_url)

test()
driver.find_element(By.ID, 'kw').send_keys('selenium')
driver.find_element(By.ID, 'su').click()

print()
print('After search====================')
test()
# 打印搜索结果条数的文本
num = driver.find_element(By.XPATH, '//*[@id="tsn_inner"]/div[2]/span').text
print('result:' + num)

# 搜索前后获取的title、current_url、text等验证信息,可以用作自动化测试的断言

6. wait

There are two types of element waiting in webdriver: explicit waiting and implicit waiting.

show wait

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

driver = webdriver.Chrome()
driver.get("https://www.baidu.com")
"""
WebDriverWait(driver, timeout, poll_frequency=0.5, ignored_exceptions=None)
在设置的时间内,默认每隔一段时间检查一次当前页面元素是否存在,如果超时,就抛出异常。
WebDriverWait()一般与until()或until_not()配合使用。until(method, message=''),
expected_conditions中包含多种预期条件判断方法,用于传入method。
"""
e = WebDriverWait(driver, 5, 0.5).until(EC.visibility_of_element_located((By.ID, 'kw')))
e.send_keys('selenium')
driver.close()

implicit wait

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.common.exceptions import NoSuchElementException
from time import ctime

driver = webdriver.Chrome()
driver.implicitly_wait(5)  # 设置显示等待时间,单位是s
driver.get('https://www.baidu.com')

# 在等待时间里一直找元素,找到了会继续执行程序,到最后都找不到的话,就会抛出异常
try:
    print(ctime())
    driver.find_element(By.ID, 'kw_no').send_keys('selenium')
except NoSuchElementException as e:
    print(e)
finally:
    print(ctime())
    driver.close()

insert image description here

7. Form and window switching

form toggle

Switch to the case of the login form:

from selenium import webdriver
from selenium.webdriver.common.by import By
import time

driver = webdriver.Chrome()
driver.get('http://www.126.com')
driver.maximize_window()
time.sleep(2)

"""
由于webdriver只能在一个页面上识别和定位元素,一开始是在最外层的,所以要先定位到表单,然后切换到登录表单里去。
switch_to.frame()默认可以直接传入表单的id或name值。该登录表单的id值是x-URS-iframe1665184560161.8542,
后面一串数字是随机变化的,于是采用css定位,用'^='来筛选以'x-URS-iframe'开头的元素,达到定位目的。
"""
login_frame = driver.find_element(By.CSS_SELECTOR, 'iframe[id^="x-URS-iframe"]')
driver.switch_to.frame(login_frame)
driver.find_element(By.NAME, 'email').send_keys('username')
driver.find_element(By.NAME, 'password').send_keys('password')
driver.find_element(By.ID, 'dologin').click()
# 切换到最外层的页面
driver.switch_to.default_content()

driver.close()

insert image description here

window switching

Example of switching between Baidu's homepage and account registration page:

from selenium import webdriver
from selenium.webdriver.common.by import By
import time


driver = webdriver.Chrome()
driver.implicitly_wait(10)
driver.get("http://www.baidu.com")
driver.maximize_window()

# 获取当前窗口(百度首页)的句柄
search_windows = driver.current_window_handle

driver.find_element(By.LINK_TEXT, '登录').click()
driver.find_element(By.LINK_TEXT, '立即注册').click()

# 虽然打开了注册页面,但是焦点还是在最初的首页,所以要切换句柄
# 获取当前所有打开的窗口句柄
all_handles = driver.window_handles

# 进入注册窗口
for handle in all_handles:
    if handle != search_windows:
        driver.switch_to.window(handle)
        print(driver.title)
        driver.find_element(By.NAME, 'userName').send_keys('username')
        driver.find_element(By.NAME, 'phone').send_keys('13500000000')
        time.sleep(2)
        driver.close()

driver.switch_to.window(search_windows)  # 切换窗口
print(driver.title)
time.sleep(2)
driver.quit()

8. Warning box, drop-down box processing

warning box

from selenium import webdriver
from selenium.webdriver.common.by import By
import time

driver = webdriver.Chrome()
driver.get('https://www.baidu.com')
driver.maximize_window()

driver.find_element(By.ID, 's-usersetting-top').click()
driver.find_element(By.LINK_TEXT, '搜索设置').click()
driver.find_element(By.LINK_TEXT, '保存设置').click()

# 获取警告框
alert = driver.switch_to.alert

time.sleep(2)
# 打印警告框提示信息
print(alert.text)

# 接受警告框
alert.accept()

drop down box

(1) select type drop-down box

# 要导入Select类
from selenium.webdriver.support.select import Select

# 先定位到下拉框元素sel,有3种方法选择要定位的下拉项:
Select(sel).select_by_index(index)  # 索引
Select(sel).select_by_value(value)  # value属性的值
Select(sel).select_by_visible_text(text)  # 选项中的文本

(2) Non-select type drop-down box

from selenium import webdriver
from selenium.webdriver.common.by import By
import time


driver = webdriver.Chrome()
driver.get('https://www.baidu.com')
driver.maximize_window()

# 定位设置按钮
driver.find_element(By.ID, 's-usersetting-top').click()
driver.find_element(By.LINK_TEXT, '高级搜索').click()

# 定位到‘全部时间’下拉框
sel = driver.find_element(By.XPATH, '//*[@id="adv-setting-gpc"]/div')
print(sel.text)
# 这里的点击必不可少
sel.click()
time.sleep(2)
# 和select类型下拉框不同,这里直接定位到“最近一天”这个选项
driver.find_element(By.XPATH, '//*[@id="adv-setting-gpc"]/div/div[2]/div[2]/p[2]').click()
print(sel.text)

driver.quit()

9. Cookie operation

Sometimes it is necessary to obtain, modify and other operations to verify the correctness of the cookie.

'''相关方法'''
get_cookies()  # 获取所有cookie
get_cookie(name)  # 返回字典中key为‘name’的cookie
add_cookie(coolie_dict)  # 添加
delete_cookie(name)  # 删除
delete_all_cookies()  

3. Overview of the automated test model

Automated test models are divided into:

1. Linearity test

A form of early automated testing that simply simulates a user's complete operating scenario. Corresponding linear scripts are generated by recording or writing the operation steps of the corresponding application program, and each script is relatively independent without any dependency or call.

2. Modularization and class library

On the basis of linear testing, repeated operations are encapsulated into common modules. When needed in the testing process, the module can be called directly, which reduces unnecessary operations and improves the maintainability of test cases.

3. Data-driven testing

Changes in data drive the execution of automated tests, and ultimately cause changes in test results. That is, to parameterize the test data required for data-driven, there are multiple ways to store and manage these parameterized data. For example, the user name and password to be tested when the user logs in are replaced by the two parameters user and password in the script, and the user name and password of different test cases are definitely different, so they are unified in one xml file ( There are also formats such as Jason, txt, CSV).

4. Keyword-driven testing

Also called table-driven testing or action-based testing. The basic work of a framework for keyword-driven testing (such as Robot Framework) is to divide test cases into four parts: test steps, objects in test steps (page objects or elements, such as user names, passwords), actions performed by test objects, and test The data required by the object.

Its core idea is to separate coding from test cases and test steps, avoiding direct contact with code by testers, so that manual testers can also write automated scripts. Most of them "write" scripts in the form of "filling in forms".

Guess you like

Origin blog.csdn.net/m0_61251376/article/details/127837900