Table of Contents
1 Automated testing
1.1 Unit testing
1.2 Interface testing
1.3 UI Test
1.3.1 Advantages of UI automated testing
1.3.2 Applicable objects for UI automated testing
1.4 Automated testing process
2 selenium
3 selenium IDE recording script
Home Backend Development Python Tutorial How to use selenium, the Python automated testing tool

How to use selenium, the Python automated testing tool

May 17, 2023 am 10:43 AM
python selenium

    1 Automated testing

    Automated testing refers to the automation of software testing, running applications or systems under preset conditions. Preset conditions include normal and abnormal , and finally evaluate the running results. The process of converting human-driven testing behavior into machine execution.

    How to use selenium, the Python automated testing tool

    Automated testing includes UI automation, interface automation, and unit test automation. Automated test planning according to this pyramid model can produce the best automated test output-to-input ratio (ROI) and obtain good benefits with less investment.

    1.1 Unit testing

    The biggest investment should be in unit testing, and unit testing should be run more frequently.

    Java’s unit testing framework is Junit.

    1.2 Interface testing

    Interface testing is API testing. Compared with UI automation, API automation is easier to implement and more stable to execute.

    Interface automation has the following characteristics:

    • It can be intervened in the early stage of the product and after the interface is completed

    • The amount of use case maintenance is small

    • Suitable for projects with small interface changes and frequent interface changes

    Common interface automation testing tools include RobotFramework, JMeter, SoapUI, TestNG HttpClient, Postman, etc.

    1.3 UI Test

    Although the testing pyramid tells us to do as much automated testing of the API layer as possible, automated testing of the UI layer is closer to the needs of users and the actual business of the software system . And sometimes we have to perform UI layer testing.

    Features of UI automation:

    • Large amount of use case maintenance

    • The page is highly relevant and must be developed later on the project page Later intervention

    • UI testing is suitable for projects with small interface changes

    There are many testing frameworks for the UI layer, such as Windows client testing AutoIT, selenium for web testing and TestPlant, eggPlant, Robot framework, QTP, etc.

    1.3.1 Advantages of UI automated testing

    Reduce the human investment in large-scale regression testing caused by changes or multi-phase development of large systems. This may be the most important task of automated testing. Especially when the program is modified frequently, the effect is very obvious. In the early stage of automated testing, more manpower is invested, but after entering the maintenance period, a lot of manpower can be saved, while in the later stage of manual testing, a lot of manpower is needed for regression testing

    • Reduce the time of repeated testing and achieve rapid regression testing

    • Create an excellent and reliable testing process and reduce human errors

    • Can run more and more tedious tests

    • Can perform some tests that are difficult or impossible to test manually

    • Better utilization Resources

    • Reusability of test scripts

    1.3.2 Applicable objects for UI automated testing

    Those who implement automated testing Prerequisites: requirements change infrequently, project cycle is long enough, and automated test scripts can be reused.

    Suitable for automation projects:

    • Product type projects. For product-type projects, the new version is an improvement on the old version, and the functions of the project are not changed much. However, the new and old functions of the project must be repeatedly regression tested. The advantage of automated testing is regression testing, which can effectively verify whether new defects have been introduced and whether old defects have been fixed. To a certain extent, automated testing tools can be called regression testing tools.

    • Test mechanically and frequently. In a long-term project, the same large amounts of data need to be entered over and over again. Such as compatibility testing.

    The following projects are not suitable for automated testing:

    • Projects with frequent demand changes, automated scripts cannot be reused, and maintenance costs are too high , low cost performance

    • The project cycle is short, the automated script is not used many times after completion, and the cost performance is low

    • A project with strong interaction, For projects that require manual intervention, automation cannot be implemented

    1.4 Automated testing process

    • Analysis: Overall grasp the system logic and analyze the core system of the system architecture.

    • Design: Design test cases. The test cases should be clear and clear enough, with broad and precise coverage.

    • Implementation: Implementation scripts, there are two The first requirement is assertion, and the second requirement is reasonable use of parameterization.

    • Execution: Executing the script is far from as simple as we imagined. Abnormalities during script execution require us to carefully analyze the causes.

    • Summary: Analysis of test results and summary of the test process are the keys to automated testing.

    • Maintenance: The maintenance of automated test scripts is a problem that is difficult to solve but must be solved.

    • Analysis: In-depth analysis of the coverage risks of automated use cases and the cost of script maintenance during the automated testing process.

    2 selenium

    Selenium is a UI-based automated testing framework for web applications, supporting multiple platforms, multiple browsers, and multiple languages.

    The early selenium RC has been replaced by the current webDriver, which can be simply understood as the selenium1.0 webdriver, and the current Selenium2.0. Typically, we use the term "Selenium" to refer to Selenium 2.0. Selenium includes three components: Selenium IDE, Webdriver and Selenium Grid.

    Let’s make an introduction respectively:

    Selenium IDE

    Selenium IDE is a complete integrated development environment for Selenium testing. It can directly record user operations in the browser, and can Playback, edit and debug test scripts. During debugging, you can step through the execution or adjust the execution speed, and view the log at the bottom for error information. The recorded test scripts can be exported in multiple languages, such as Java, C#, Python, Ruby, etc., making it easier for testers who master different languages ​​to operate. Webdriver

    Selenium RC When running JavaScript applications in a browser, there will be environmental sandbox issues, but WebDriver can jump out of the JavaScript sandbox and create more robust, distributed, and cross-platform applications for different browsers. Automated test scripts. Based on specific language (Java, C#, Python, Ruby, Perl, JavaScript, etc.) bindings to drive the browser to operate and validate web elements.

    How webdriver works:

    • After starting the browser, selenium-webdriver will bind the target browser to a specific port, and the started browser will act as webdriver's remote server.

    • The client (that is, the test script) uses ComandExecutor to send an HTTP request to the server (communication protocol: The WebDriver Wire Protocol. In the body of the HTTP request, the WebDriver Wire protocol will be used. A specified JSON-formatted string that tells Selenium what we want the browser to do next).

    • The Sever side needs to rely on native browser components and convert Web Service commands into browser native calls to complete the operation.

    selenium Grid

    selenium Grid is a server that provides a list of servers accessed by browser instances and manages the registration and status information of each node. Different test scripts can be executed on different servers at the same time.

    3 selenium IDE recording script

    Open Edge-plug-in-select selenium IDE:

    Create a new project, and there will be an Untitled test in the Test Case window on the left Case, right-click and rename it to "test"

    How to use selenium, the Python automated testing tool

    Click the recording button (little red dot) in the upper right part of the IDE to start manual recording

    In the address bar Enter the URL to be tested, such as http://www.baidu.com, search for keywords, and you can see that the IDE is recording.

    Right-click on the page to add checkpoints.

    After the recording is completed, click the recording button (little red dot) to end this manual recording. In selenium IDE, select a Test Case, right-click and select "Export as a test.py file.

    Run the script in python and debug it.

    # Generated by Selenium IDE
    import pytest
    import time
    import json
    from selenium import webdriver
    from selenium.webdriver.common.by import By
    from selenium.webdriver.common.action_chains import ActionChains
    from selenium.webdriver.support import expected_conditions
    from selenium.webdriver.support.wait import WebDriverWait
    from selenium.webdriver.common.keys import Keys
    from selenium.webdriver.common.desired_capabilities import DesiredCapabilities
    class TestTest():
      def setup_method(self, method):
        self.driver = webdriver.Chrome()
        self.vars = {}
      def teardown_method(self, method):
        self.driver.quit()
      def test_test(self):
        self.driver.get("https://www.baidu.com/")
        self.driver.set_window_size(809, 864)
        self.driver.find_element(By.ID, "kw").click()
        self.driver.execute_script("window.scrollTo(0,0)")
        self.driver.find_element(By.ID, "kw").send_keys("四月是你的谎言")
        self.driver.find_element(By.ID, "su").click()

    The above is the detailed content of How to use selenium, the Python automated testing tool. For more information, please follow other related articles on the PHP Chinese website!

    Statement of this Website
    The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

    Hot AI Tools

    Undress AI Tool

    Undress AI Tool

    Undress images for free

    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.

    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

    Notepad++7.3.1

    Notepad++7.3.1

    Easy-to-use and free code editor

    SublimeText3 Chinese version

    SublimeText3 Chinese version

    Chinese version, very easy to use

    Zend Studio 13.0.1

    Zend Studio 13.0.1

    Powerful PHP integrated development environment

    Dreamweaver CS6

    Dreamweaver CS6

    Visual web development tools

    SublimeText3 Mac version

    SublimeText3 Mac version

    God-level code editing software (SublimeText3)

    Hot Topics

    PHP Tutorial
    1500
    276
    PHP calls AI intelligent voice assistant PHP voice interaction system construction PHP calls AI intelligent voice assistant PHP voice interaction system construction Jul 25, 2025 pm 08:45 PM

    User voice input is captured and sent to the PHP backend through the MediaRecorder API of the front-end JavaScript; 2. PHP saves the audio as a temporary file and calls STTAPI (such as Google or Baidu voice recognition) to convert it into text; 3. PHP sends the text to an AI service (such as OpenAIGPT) to obtain intelligent reply; 4. PHP then calls TTSAPI (such as Baidu or Google voice synthesis) to convert the reply to a voice file; 5. PHP streams the voice file back to the front-end to play, completing interaction. The entire process is dominated by PHP to ensure seamless connection between all links.

    How to use PHP combined with AI to achieve text error correction PHP syntax detection and optimization How to use PHP combined with AI to achieve text error correction PHP syntax detection and optimization Jul 25, 2025 pm 08:57 PM

    To realize text error correction and syntax optimization with AI, you need to follow the following steps: 1. Select a suitable AI model or API, such as Baidu, Tencent API or open source NLP library; 2. Call the API through PHP's curl or Guzzle and process the return results; 3. Display error correction information in the application and allow users to choose whether to adopt it; 4. Use php-l and PHP_CodeSniffer for syntax detection and code optimization; 5. Continuously collect feedback and update the model or rules to improve the effect. When choosing AIAPI, focus on evaluating accuracy, response speed, price and support for PHP. Code optimization should follow PSR specifications, use cache reasonably, avoid circular queries, review code regularly, and use X

    python seaborn jointplot example python seaborn jointplot example Jul 26, 2025 am 08:11 AM

    Use Seaborn's jointplot to quickly visualize the relationship and distribution between two variables; 2. The basic scatter plot is implemented by sns.jointplot(data=tips,x="total_bill",y="tip",kind="scatter"), the center is a scatter plot, and the histogram is displayed on the upper and lower and right sides; 3. Add regression lines and density information to a kind="reg", and combine marginal_kws to set the edge plot style; 4. When the data volume is large, it is recommended to use "hex"

    PHP integrated AI emotional computing technology PHP user feedback intelligent analysis PHP integrated AI emotional computing technology PHP user feedback intelligent analysis Jul 25, 2025 pm 06:54 PM

    To integrate AI sentiment computing technology into PHP applications, the core is to use cloud services AIAPI (such as Google, AWS, and Azure) for sentiment analysis, send text through HTTP requests and parse returned JSON results, and store emotional data into the database, thereby realizing automated processing and data insights of user feedback. The specific steps include: 1. Select a suitable AI sentiment analysis API, considering accuracy, cost, language support and integration complexity; 2. Use Guzzle or curl to send requests, store sentiment scores, labels, and intensity information; 3. Build a visual dashboard to support priority sorting, trend analysis, product iteration direction and user segmentation; 4. Respond to technical challenges, such as API call restrictions and numbers

    python list to string conversion example python list to string conversion example Jul 26, 2025 am 08:00 AM

    String lists can be merged with join() method, such as ''.join(words) to get "HelloworldfromPython"; 2. Number lists must be converted to strings with map(str, numbers) or [str(x)forxinnumbers] before joining; 3. Any type list can be directly converted to strings with brackets and quotes, suitable for debugging; 4. Custom formats can be implemented by generator expressions combined with join(), such as '|'.join(f"[{item}]"foriteminitems) output"[a]|[

    Optimizing Python for Memory-Bound Operations Optimizing Python for Memory-Bound Operations Jul 28, 2025 am 03:22 AM

    Pythoncanbeoptimizedformemory-boundoperationsbyreducingoverheadthroughgenerators,efficientdatastructures,andmanagingobjectlifetimes.First,usegeneratorsinsteadofliststoprocesslargedatasetsoneitematatime,avoidingloadingeverythingintomemory.Second,choos

    python connect to sql server pyodbc example python connect to sql server pyodbc example Jul 30, 2025 am 02:53 AM

    Install pyodbc: Use the pipinstallpyodbc command to install the library; 2. Connect SQLServer: Use the connection string containing DRIVER, SERVER, DATABASE, UID/PWD or Trusted_Connection through the pyodbc.connect() method, and support SQL authentication or Windows authentication respectively; 3. Check the installed driver: Run pyodbc.drivers() and filter the driver name containing 'SQLServer' to ensure that the correct driver name is used such as 'ODBCDriver17 for SQLServer'; 4. Key parameters of the connection string

    python pandas melt example python pandas melt example Jul 27, 2025 am 02:48 AM

    pandas.melt() is used to convert wide format data into long format. The answer is to define new column names by specifying id_vars retain the identification column, value_vars select the column to be melted, var_name and value_name, 1.id_vars='Name' means that the Name column remains unchanged, 2.value_vars=['Math','English','Science'] specifies the column to be melted, 3.var_name='Subject' sets the new column name of the original column name, 4.value_name='Score' sets the new column name of the original value, and finally generates three columns including Name, Subject and Score.

    See all articles