1. Mouse positioning operation
Mouse hover, which is an event triggered when the cursor overlaps the element represented by its name. In Selenium, keyboard and mouse operations are
The operation is encapsulated in the Action Chains class. The main application scenarios of the Action Chains class are mouse click, double click, and mouse drag.
Drag and wait. Some commonly used methods are classified as follows:
• click(on_element=None), simulates a mouse click operation.
• click_and_hold(on_element=None), simulates a mouse click and hold.
• double_click(on_element=None), simulates a double mouse click.
• context_click(on_element=None), simulates a right mouse click operation.
• drag_and_drop(source,target), simulates mouse dragging.
• drag_and_drop(source,xoffset,yoffset), simulates dragging the target to the target location.
• key_down(value,element=None), simulates pressing a certain key to implement shortcut key operations.
• key_up(value,element=None), simulates releasing a key, and is generally used together with the key_down operation.
• move_to_element(to_element), simulates moving the mouse to a specified page element.
• move_to_element_with_offset(to_element,xoffset,yoffset), moves the mouse to the specified coordinates.
• perform(), executes the previous series of ActionChains.
• release(on_element=None), releases the pressed mouse.
Next, two examples are listed: right-click operation and double-click operation.
(1) Right-click the mouse to realize right-click/double-click the "News" hyperlink on Baidu homepage. code show as below:
# _*_ coding:utf-8 _*_
"""
name:zhangxingzai
date:2023/2/16
form:《Selenium 3+Python 3自动化测试项目实战》
"""
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver import ActionChains
driver = webdriver.Firefox()
# 打开百度
driver.get('https://www.baidu.com/')
# 定位超链接‘新闻’
element = driver.find_element(By.LINK_TEXT, '新闻')
# 实现在新闻超链接上右击
ActionChains(driver).context_click(element).perform()
# 实现用鼠标实现双击‘新闻’
ActionChains(driver).double_click(element).perform()
(2) Taking Baidu homepage settings as an example, use the "move_to_element" method to hover the mouse over the element settings:
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver import ActionChains
driver = webdriver.Firefox()
# 打开百度
driver.get('https://www.baidu.com/')
# 通过id定位超链接‘设置’
setting = driver.find_element(By.ID, 's-usersetting-top')
# 使用方法 move_to_element 模拟将鼠标悬停在超链接“设置”处
ActionChains(driver).move_to_element(setting).perform()
# 定位超链接‘高级设置’,并实现单击操作
driver.find_element(By.CLASS_NAME, 'set').click()
The effect is as follows:
2.Select operation
Drop-down box options are often encountered on Web pages. The Select module provides a variety of operations for the standard Select drop-down box.
Law. Open Baidu, click "Settings → Advanced Settings", a Select drop-down box will appear, as shown in the figure below:
The HTML code for the Select element is shown below.
Next, we introduce three methods of selecting the value of the Select element.
Select class: used to locate labels.
select_by_value(): Locate drop-down options by value value.
select_by_visible_text(): Locate drop-down options by text value.
select_by_index(): Select based on the index of the drop-down option. The first option is 0 and the second option is 1.
Operate the drop-down box through WebDriver code, the code is as follows:
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver import ActionChains
from selenium.webdriver.support.select import Select
driver = webdriver.Firefox()
# 打开百度
driver.get('https://www.baidu.com/')
# 定位超链接‘设置’
setting = driver.find_element(By.ID, 's-usersetting-top')
# 使用方法 move_to_element 模拟将鼠标悬停在超链接“设置”处
ActionChains(driver).move_to_element(setting).perform()
# 通过xpath定位超链接‘高级’,并实现单击操作
driver.find_element(By.XPATH, "//div/a[@target='_blank']/span").click()
# 通过class定位选择‘全部时间’
search_time = driver.find_element(By.CLASS_NAME, 'c-select-selection')
# 通过 value 值定位下拉选项
Select(search_time).select_by_value('stf=1676475129.442,1676561529.442|stftype=1')
# 通过 text 值定位下拉选项
Select(search_time).select_by_visible_text('最近一周')
3.Keyboard operation
As introduced before, the send_keys() method can be used to simulate keyboard input. We can also use it to input on the keyboard.
keys, even key combinations, such as Ctrl+a, Ctrl+c, etc.
After summary, the following are the keyboard events commonly used in automated testing.
• Keys.BACK_SPACE: Delete keys.
• Keys.SPACE: Space bar.
• Keys.TAB: Tab key.
• Keys.ESCAPE: Escape key.
• Keys.ENTER: Enter key.
• Keys.CONTROL,"a": Key combination Ctrl + A.
• Keys.CONTROL,"x": Key combination Ctrl + X.
• Keys.CONTROL,"v": Key combination Ctrl + V.
• Keys.CONTROL,"c": Key combination Ctrl + C.
• Keys.F1: F1 key.
• Keys.F12: F12 key.
Usage examples are shown in the following code:
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
from time import sleep
driver = webdriver.Firefox()
# 打开百度
driver.get('https://www.baidu.com/')
# 在输入框输入内容
driver.find_element(By.ID, "kw").send_keys("selenium")
# 删除多输入的一个 m
driver.find_element(By.ID, "kw").send_keys(Keys.BACK_SPACE)
sleep(1)
# 输入空格键+“教程”
driver.find_element(By.ID, "kw").send_keys(Keys.SPACE)
driver.find_element(By.ID, "kw").send_keys("教程")
sleep(1)
# 输入组合键 Ctrl+a,全选输入框内容
driver.find_element(By.ID, "kw").send_keys(Keys.CONTROL, 'a')
sleep(1)
# 输入组合键 Ctrl+x,剪切输入框内容
driver.find_element(By.ID, "kw").send_keys(Keys.CONTROL, 'x')
sleep(1)
# 输入组合键 Ctrl+v,粘贴内容到输入框
driver.find_element(By.ID, "kw").send_keys(Keys.CONTROL, 'v')
sleep(1)
# 用回车键代替单击操作
driver.find_element(By.ID, "su").send_keys(Keys.ENTER)
4. Use JavaScript to operate page elements
WebDiver does not directly support controls on some browsers, such as the scroll bar on the right side of the browser, paratext, etc., but
Usually done indirectly with the help of JavaScript. WebDriver provides two methods: execute_script() and execute_async_scrip().
Methods to execute JavaScript code, the differences are as follows:
(1) execute_script is executed synchronously and has a short execution time. WebDriver will wait for the result of synchronous execution,
Then execute subsequent code.
(2) execute_async_script is executed asynchronously and takes a long time to execute. WebDriver does not wait for asynchronous execution
The result of the code, but the subsequent code is executed directly.
The JavaScript code used to adjust the position of the browser scroll bar is as follows.
<!-- window.scrollTo(左边距,上边距); -->
window.scrollTo(0,450);
The window.scrollTo() method is used to set the horizontal and vertical positions of the browser window scroll bar. first parameter
Represents the horizontal left margin, and the second parameter represents the vertical top margin. The code is as follows.
from selenium import webdriver
from selenium.webdriver.common.by import By
from time import sleep
driver = webdriver.Firefox()
# 打开百度
driver.get('https://www.baidu.com/')
# 设置浏览器窗口大小
driver.set_window_size(800, 700)
driver.find_element(By.ID, "kw").send_keys("selenium")
driver.find_element(By.ID, "su").click()
sleep(3)
# 通过 JavaScript 设置浏览器窗口的滚动条位置
js = "window.scrollTo(100,300)"
driver.execute_script(js)
The execution result is shown in the figure below:
5. Obtain verification information
In web automated testing, the most commonly used verification information is title, current_url and text.
-
title: used to get the title of the current page.
-
current_url: used to get the URL of the current page.
-
text: used to obtain the text information of the current page.
The following still uses Baidu search as an example to compare the information before and after the search.
from selenium import webdriver
from selenium.webdriver.common.by import By
from time import sleep
driver = webdriver.Firefox()
driver.get('https://www.baidu.com/')
print('Before search================')
# 打印当前页面 title
title = driver.title
print("title:" + title)
# 打印当前页面 URL
now_url = driver.current_url
print("URL:" + now_url)
driver.find_element(By.ID, "kw").send_keys("selenium")
driver.find_element(By.ID, "su").click()
sleep(3)
print('After search================')
# 再次打印当前页面 title
title = driver.title
print("title:" + title)
# 再次打印当前页面 URL
now_url = driver.current_url
print("URL:" + now_url)
# 获取搜索结果条数
num = driver.find_element(By.XPATH, "//span[@class='hint_PIwZX c_font_2AD7M']").text
print("result:"+num)
The running results are as follows:
Through the above printed information, you can see the difference before and after the search. This difference information can be used as assertion points for automated testing.
6. Set elements to wait
WebDriver provides two types of element waits: explicit waits and implicit waits.
(1) Display waiting
Explicit waiting means that WebDriver waits for a certain condition to be true and then continues execution, otherwise it throws a timeout when the maximum duration is reached.
TimeoutException.
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.Firefox()
driver.get("https://www.baidu.com")
element = WebDriverWait(driver, 5, 0.5).until(
EC.visibility_of_element_located((By.ID, "kw"))
)
element.send_keys('selenium')
The WebDriverWait class is the wait method provided by WebDriver. Within the set time, the default is to check every
Test once whether the current page element exists. If it cannot be detected after the set time, an exception will be thrown.
The specific format is as follows.
The WebDriverWait class is the wait method provided by WebDriver. Within the set time, the default is to check every
Test once whether the current page element exists. If it cannot be detected after the set time, an exception will be thrown.
The specific format is as follows.
-
driver: browser driver.
-
timeout: the maximum timeout time, the default unit is seconds.
-
poll_frequency: detection interval (step) time, the default is 0.5s.
-
ignored_exceptions: Exception information after timeout, NoSuchElementException exception is thrown by default.
WebDriverWait() is generally used in conjunction with the until() or until_not() method. The following are until() and until_not()
Description of method:
until(method, message=″)
Call this method providing the driver as a parameter until the return value is True.
until_not(method, message=″)
Call this method providing the driver as a parameter until the return value is False.
In this example, expect_conditions is renamed to EC through the as keyword, and the presence_of_element_located() method is called to determine whether the element exists.
The expected condition judgment method provided by the expected_conditions class is shown in the figure below.
In addition to the rich expected condition judgment methods provided by the expected_conditions class, you can also use the is_displayed() method to implement element display waiting by yourself.
from time import sleep, ctime
from selenium import webdriver
from selenium.webdriver.common.by import By
driver = webdriver.Firefox()
driver.get("https://www.baidu.com")
print(ctime())
for i in range(10):
try:
el = driver.find_element(By.ID, "kw22")
if el.is_displayed():
break
except:
pass
sleep(1)
else:
print("time out")
print(ctime())
Relatively speaking, this method is easier to understand. First, the for loop is performed 10 times, and then the is_displayed() method is used to loop to determine whether the element is visible. If it is True, the element is visible, and break is executed to exit the loop;
Otherwise, execute sleep() to sleep for 1s and then continue to loop and judge. After 10 loops, if break is not executed, the else statement corresponding to the for loop is executed and "time out" information is printed.
Here, the id positioning is deliberately set to "kw22", but the positioning fails. The execution results are as follows:
(2) Implicit waiting
The implicitly_wait() method provided by WebDriver can be used to implement implicit waiting, and its usage is relatively simple.
from time import ctime
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.common.exceptions import NoSuchElementException
driver = webdriver.Firefox()
# 设置隐式等待为 10s
driver.implicitly_wait(10)
driver.get("https://www.baidu.com")
try:
print(ctime())
driver.find_element(By.ID, "kw22").send_keys('selenium')
except NoSuchElementException as e:
print(e)
finally:
print(ctime())
The parameter of implicitly_wait() is time in seconds. The waiting time set in this example is 10s.
First of all, this 10s is not a fixed waiting time, and it does not affect the execution speed of the script. Second, it will wait for all the
element. When the script is executed to locate an element, if the element exists, execution will continue; if the element cannot be located,
Then it will continuously determine whether the element exists in a polling manner. Assuming that the element is located at 6s, execution continues,
If the element is not located until the set time (10s) is exceeded, an exception will be thrown.
Here, the id positioning is also deliberately set to "kw22". The positioning fails and the execution results are as follows:
7. Warning box processing
It is very simple to process alert, confirm and prompt generated by JavaScript in WebDriver. The specific method is:
First use the switch_to.alert() method to locate, and then use text, accept, dismiss, send_keys, etc. to operate.
-
text: Returns the text information in alert, confirm, and prompt.
-
accept(): Accept the existing warning box.
-
dismiss(): Dismiss the existing warning box.
-
send_keys(): Enter text in the alert box (if input is possible).
Here we take Baidu search settings as an example. Open Baidu search settings. After the settings are completed, click the "Save Settings" button. You can use the switch_to.alert() method to set a pop-up window for Baidu search, as shown in the following figure:
code show as below:
from time import sleep
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver import ActionChains
driver = webdriver.Firefox()
driver.get('https://www.baidu.com/')
# 定位超链接‘设置’
setting = driver.find_element(By.ID, 's-usersetting-top')
# 使用方法 move_to_element 模拟将鼠标悬停在超链接“设置”处
ActionChains(driver).move_to_element(setting).perform()
# 通过class定位超链接‘搜索设置’,并实现单击操作
driver.find_element(By.CLASS_NAME, "set").click()
# 通过xpath获取保存设置
driver.find_element(By.XPATH, "//a[@class='prefpanelgo setting-btn c-btn c-btn-primary']").click()
sleep(3)
# 获取警告框
alert = driver.switch_to.alert
# 获取警告框提示信息
alert_text = alert.text
print(alert_text)
# 接取警告框
alert.accept()
8. Get Cookies
Sometimes we need to verify whether the cookies in the browser are correct, because real cookies cannot pass
White box testing and integration testing. WebDriver provides related methods for operating Cookies, which can read, add and delete
Except cookies.
-
WebDriver operates Cookies as follows:
-
get_cookies(): Get all cookies.
-
get_cookie(name): Returns the cookie whose key is "name" in the dictionary.
-
add_cookie(cookie_dict):添加 Cookie。
-
delete_cookie(name,optionsString): Delete the cookie named OpenString.
-
delete_all_cookies(): Delete all cookies.
Next, get all cookies of the current browser through get_cookies(). code show as below:
from selenium import webdriver
driver = webdriver.Firefox()
driver.get('https://www.baidu.com/')
# 获得所有 Cookie 信息并打印
cookie = driver.get_cookies()
print(cookie)
The execution results are as follows:
As can be seen from the execution results, the data in the cookie is stored in dictionary form. Know the data in cookies
Once the form is saved, cookies can be added to the browser in this form.
from selenium import webdriver
driver = webdriver.Firefox()
driver.get('https://www.baidu.com/')
# 添加 Cookie 信息
driver.add_cookie({'name': 'foo', 'value': 'bar'})
# 遍历指定的 Cookies
for cookie in driver.get_cookies():
print("%s -> %s" % (cookie['name'], cookie['value']))
The execution results are as follows:
It can be seen from the execution results that the last cookie was added through the add_cookie() method during script execution.
Added. Get all the cookies by traversing to find the cookies with keys "name" and "value" in the dictionary
value.
The use of delete_cookie() and delete_all_cookies() methods is also very simple. The former deletes a cookie by name.
Specified cookies, the latter directly deletes all cookies in the browser.
9. Window screenshot
Automated test cases are executed by programs, so sometimes the error messages printed are not intuitive enough. if in script
When an execution error occurs, you can take a screenshot of the current window and save it. Then you can see the script output very intuitively through the screenshot.
Wrong reason. WebDriver provides the screenshot function save_screenshot (), which can be used to capture the current window.
from time import sleep
from selenium import webdriver
driver = webdriver.Firefox()
driver.get('https://www.baidu.com/')
sleep(3)
# 截取当前窗口,指定截图图片的保存位置
driver.save_screenshot("D:/baidu_img.png")
WebDriver recommends using png as the suffix name of the image. After the script is completed, the baidu_img.png image will be generated in the root directory of drive D.
10.Slider operation
As a kind of security verification mechanism, the slider is often involved when logging in or registering. But when automating testing, you need to find a way to handle the slider in code. The following takes the registration page of Ctrip.com as an example to demonstrate how to operate the slider. The website URL is "https://passport.ctrip.com/user/reg/home", and the process to be followed for code implementation is as follows:
Open the Ctrip registration page https://passport.ctrip.com/user/reg/home.
In the pop-up window of "Ctrip User Registration Agreement and Privacy Policy", click the "Agree and Continue" button
Display the "slider verification" function during the verification step of the mobile phone. You need to use code to drag the slider to the far right.
The operation of the slider in Selenium basically uses the element dragging method, and this method requires the use of Selenium's Actionchains function module. First find the length and width of the slider button and slider area respectively.
The elements of the slider button are as follows:
The implementation code is as follows:
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver import ActionChains
from time import sleep
driver = webdriver.Firefox()
driver.get('https://passport.ctrip.com/user/reg/home')
sleep(3)
# 通过xpath定位‘同意并继续’并点击
driver.find_element(By.XPATH, "//div/div/a[@class='reg_btn reg_agree']").click()
# 以下代码的功能是获取滑块元素
sour = driver.find_element(By.CLASS_NAME, 'cpt-drop-btn')
print( sour.size['width'])
print(sour.size['height'])
# 以下代码的功能是获取滑块区域元素
ele = driver.find_element(By.CLASS_NAME, 'cpt-bg-bar')
print( ele.size['width'])
print(ele.size['height'])
After the above code is run, the console prints the length and width of the two elements respectively.
Note that the height of the slider button and the slider area are both 40px, and their widths are 40px and 268px respectively.
Let's implement the operation of executing the slider. As mentioned in the registration business analysis, the drag operation of the slider needs to be
Use the drag_and_drop_by_offset method of the function module ActionChains. The method usage is as follows:
The complete demo code is as follows:
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver import ActionChains
from time import sleep
driver = webdriver.Firefox()
driver.get('https://passport.ctrip.com/user/reg/home')
sleep(2)
# 通过xpath定位‘同意并继续’并点击
driver.find_element(By.XPATH, "//div/div/a[@class='reg_btn reg_agree']").click()
# 以下代码的功能是获取滑块元素
sour = driver.find_element(By.CLASS_NAME, 'cpt-drop-btn')
# 以下代码的功能是获取滑块区域元素
ele = driver.find_element(By.CLASS_NAME, 'cpt-bg-bar')
# 拖动滑块
x_width = sour.size['width'] + ele.size['width']
y_height = ele.size['height']
sleep(2)
ActionChains(driver).drag_and_drop_by_offset(sour, x_width, y_height).perform()
In this way, we have learned most of Selenium's special element operation methods. Readers can master Selenium's common methods, including becoming familiar with the scenarios or prerequisites for each method.
Finally, I would like to share with you some of my learning materials:
The above content should be the most comprehensive and complete preparation warehouse for software testing friends. In order to better organize each module, I also referred to many high-quality blog posts on the Internet. and projects, trying not to miss every knowledge point. Many friends relied on these contents to review and got offers from major manufacturers such as BATJ. This warehouse has also helped many software testing learners. I hope it can also help you. .
Follow my WeChat official account below to get it for free! ↓ ↓ ↓ ↓ ↓