search
HomeBackend DevelopmentPython TutorialPython practical analysis of the basic elements of selenium and keyboard and mouse simulation events

This article brings you relevant knowledge about python, which mainly introduces the basic elements of selenium and issues related to keyboard and mouse simulation events, including the use of Keys module to simulate keyboard operation events. , use the Action class to simulate mouse operation events, etc. Let’s take a look at it together. I hope it will be helpful to everyone.

Python practical analysis of the basic elements of selenium and keyboard and mouse simulation events

Recommended learning: python video tutorial

When we locate a specific element, we can specify the element operations, such as the click operation performed in the previous chapter. This is the simplest operation, webdriver There are other operations. For example, basic operations of elements (click, input, clear), as well as some advanced operations such as mouse and keyboard simulation events, pop-up box processing, multi-page switching, etc... These are all things that we need to understand, and they are often used when doing automated testing. Some basic scenarios encountered. In today's chapter, let's first learn the basic operations of elements and the operation of mouse and keyboard simulation events.

Basic operations of elements

Use the local form.html file we used before to practice the basic click, input, and clear operations of elements.

The code example is as follows:

# coding:utf-8

from time import sleep
from selenium import webdriver


driver = webdriver.Chrome()     # 启动 Chrome浏览器的 driver
driver.maximize_window()        # Chrome 浏览器最大化
driver.get('file:///Users/workspace/WEB_TEST_HTML/form.html')       # 打开本地的 "form.html" 文件
sleep(1)
email_element = driver.find_element_by_xpath('//*[@id="inputEmail"]')    # 通过 xpath 定位 Email 输入框。
email_element.send_keys('username')     # Email 输入框输入 "username"
sleep(1)
email_element.clear()                   # 清除 Email 输入框内容
sleep(1)
email_element.send_keys('admin')        # Email 输入框输入 "admin"

driver.find_element_by_xpath('//*[@id="inputPassword"]').send_keys('123456')    # Password 输入框输入 "123456"
sleep(1)
driver.find_element_by_xpath('/html/body/form/div[3]/div/button').click()		# 通过 xpath 定位 "Sign in" 按钮并点击

driver.quit()

The running results are as follows:


Python practical analysis of the basic elements of selenium and keyboard and mouse simulation events


The above are elements Basic operations are actually the simplest and most basic operations. Next, let's continue to look at more difficult operations ---> Mouse and keyboard simulation event operations.

Mouse and keyboard simulation event operation

Use our local sendkeys.html file to implement mouse and keyboard simulation event operation. sendkeys.html The page elements of the file are as follows:


Python practical analysis of the basic elements of selenium and keyboard and mouse simulation events


##Use the Keys module to simulate keyboard operation events

ps: Using the Keys module requires an import operation: "from selenium.webdriver.common.keys import Keys"

Keyboard simulation event code examples are as follows:

# coding:utf-8

from time import sleep
from selenium import webdriver
from selenium.webdriver.common.keys import Keys

driver = webdriver.Chrome()     # 启动 Chrome浏览器的 driver
driver.maximize_window()        # Chrome 浏览器最大化
driver.get('file:///Users/workspace/WEB_TEST_HTML/sendkeys.html')   # 打开本地的 "form.html" 文件
sleep(1)

# 这里需要注意一下,因为我使用的是 Mac ,所以键盘 ctrl 事件是 "Keys.COMMAND" ,如果是 Win 系统的话,ctrl 事件是 "Keys.CONTROL"
driver.find_element_by_id('A').send_keys((Keys.COMMAND, 'a'))       # 通过 id 定位 "id = A" 的元素,执行键盘事件 command + a
driver.find_element_by_id('A').send_keys((Keys.COMMAND, 'x'))       # 通过 id 定位 "id = A" 的元素,执行键盘事件 command + x
sleep(1)
driver.find_element_by_id('B').send_keys((Keys.COMMAND, 'v'))       # 通过 id 定位 "id = B" 的元素,执行键盘事件 command + v
sleep(1)
driver.find_element_by_id('B').send_keys((Keys.COMMAND, 'a'))       # 通过 id 定位 "id = B" 的元素,执行键盘事件 command + a
sleep(1)
driver.find_element_by_id('B').send_keys((Keys.COMMAND, 'c'))       # 通过 id 定位 "id = B" 的元素,执行键盘事件 command + c
sleep(1)
driver.find_element_by_id('A').send_keys((Keys.COMMAND, 'v'))       # 通过 id 定位 "id = A" 的元素,执行键盘事件 command + v
sleep(1)

driver.quit()
Run results As follows:


Python practical analysis of the basic elements of selenium and keyboard and mouse simulation events


Use the Action class to simulate mouse operation events

PS: There are not many scenarios for simulating mouse operations. Just understand. At the same time, the Action class needs to execute "from selenium.webdriver import ActionChains"

Let's first take a look at what common mouse operations the Action class supports.

    key_down: Simulate a mouse button press
  • key_up: Simulate a mouse button pop-up
  • click: Simulate a mouse button click (click)
  • context_click: Click the right mouse button
  • double_click: Simulate a mouse button click (double-click)
  • send_keys: Send a key to the currently focused element
  • click_and_hold: Click Left mouse button, do not release (drag)
  • release: release, release the pressed mouse button
  • move_to: move the mouse to...
  • drag_and_drop: drag and drop Get up and throw it away...
  • perform: No matter what operation is done, you need to
  • perform in the end to submit
PS: It will not happen in the actual scene It uses very complex mouse operation events to write

automated Case, so what we demonstrate is also a relatively simple scenario.

Simulating mouse events The code example is as follows:

# coding:utf-8

from time import sleep
from selenium import webdriver
from selenium.webdriver import ActionChains


driver = webdriver.Chrome()     # 启动 Chrome浏览器的 driver
driver.maximize_window()        # Chrome 浏览器最大化
driver.get('file:///Users/workspace/WEB_TEST_HTML/sendkeys.html')   # 打开本地的 "form.html" 文件
sleep(1)

# 这里需要注意一下,因为我使用的是 Mac ,所以键盘 ctrl 事件是 "Keys.COMMAND" ,如果是 Win 系统的话,ctrl 事件是 "Keys.CONTROL"
double_click_element = driver.find_element_by_id('A')
# 通过 id 定位 "id = A" 的元素赋值给 double_click_element

ActionChains(driver).double_click(double_click_element).context_click(double_click_element).perform()
# 通过 ActionChains 类将 "driver" 转换,先双击、然后执行右击操作【这种串联起来的操作,叫做链式用法,可以根据这个链一直往下写】
sleep(2)

ActionChains(driver).context_click(double_click_element).perform()
# 通过 ActionChains 类将 "driver" 转换,然后执行右击操作
sleep(2)

driver.quit()
The running results are as follows:


Python practical analysis of the basic elements of selenium and keyboard and mouse simulation events

The above is Use the

Action class to implement the simulation of some special scenes. The more commonly used ones are double-click, right-click, drag and other scenes are used slightly more, and other scenes use Action There will be very few categories.

Recommended learning:

python video tutorial

The above is the detailed content of Python practical analysis of the basic elements of selenium and keyboard and mouse simulation events. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:CSDN. If there is any infringement, please contact admin@php.cn delete
Python vs. C  : Understanding the Key DifferencesPython vs. C : Understanding the Key DifferencesApr 21, 2025 am 12:18 AM

Python and C each have their own advantages, and the choice should be based on project requirements. 1) Python is suitable for rapid development and data processing due to its concise syntax and dynamic typing. 2)C is suitable for high performance and system programming due to its static typing and manual memory management.

Python vs. C  : Which Language to Choose for Your Project?Python vs. C : Which Language to Choose for Your Project?Apr 21, 2025 am 12:17 AM

Choosing Python or C depends on project requirements: 1) If you need rapid development, data processing and prototype design, choose Python; 2) If you need high performance, low latency and close hardware control, choose C.

Reaching Your Python Goals: The Power of 2 Hours DailyReaching Your Python Goals: The Power of 2 Hours DailyApr 20, 2025 am 12:21 AM

By investing 2 hours of Python learning every day, you can effectively improve your programming skills. 1. Learn new knowledge: read documents or watch tutorials. 2. Practice: Write code and complete exercises. 3. Review: Consolidate the content you have learned. 4. Project practice: Apply what you have learned in actual projects. Such a structured learning plan can help you systematically master Python and achieve career goals.

Maximizing 2 Hours: Effective Python Learning StrategiesMaximizing 2 Hours: Effective Python Learning StrategiesApr 20, 2025 am 12:20 AM

Methods to learn Python efficiently within two hours include: 1. Review the basic knowledge and ensure that you are familiar with Python installation and basic syntax; 2. Understand the core concepts of Python, such as variables, lists, functions, etc.; 3. Master basic and advanced usage by using examples; 4. Learn common errors and debugging techniques; 5. Apply performance optimization and best practices, such as using list comprehensions and following the PEP8 style guide.

Choosing Between Python and C  : The Right Language for YouChoosing Between Python and C : The Right Language for YouApr 20, 2025 am 12:20 AM

Python is suitable for beginners and data science, and C is suitable for system programming and game development. 1. Python is simple and easy to use, suitable for data science and web development. 2.C provides high performance and control, suitable for game development and system programming. The choice should be based on project needs and personal interests.

Python vs. C  : A Comparative Analysis of Programming LanguagesPython vs. C : A Comparative Analysis of Programming LanguagesApr 20, 2025 am 12:14 AM

Python is more suitable for data science and rapid development, while C is more suitable for high performance and system programming. 1. Python syntax is concise and easy to learn, suitable for data processing and scientific computing. 2.C has complex syntax but excellent performance and is often used in game development and system programming.

2 Hours a Day: The Potential of Python Learning2 Hours a Day: The Potential of Python LearningApr 20, 2025 am 12:14 AM

It is feasible to invest two hours a day to learn Python. 1. Learn new knowledge: Learn new concepts in one hour, such as lists and dictionaries. 2. Practice and exercises: Use one hour to perform programming exercises, such as writing small programs. Through reasonable planning and perseverance, you can master the core concepts of Python in a short time.

Python vs. C  : Learning Curves and Ease of UsePython vs. C : Learning Curves and Ease of UseApr 19, 2025 am 12:20 AM

Python is easier to learn and use, while C is more powerful but complex. 1. Python syntax is concise and suitable for beginners. Dynamic typing and automatic memory management make it easy to use, but may cause runtime errors. 2.C provides low-level control and advanced features, suitable for high-performance applications, but has a high learning threshold and requires manual memory and type safety management.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor