Python+Selenium+Chrome自动化测试(简单版)

Python3.8

Python3.8

Conda
Python

Python 是一种高级、解释型、通用的编程语言,以其简洁易读的语法而闻名,适用于广泛的应用,包括Web开发、数据分析、人工智能和自动化脚本

一、实验目的

           通过Selenium自动化测试工具,实现对Web应用程序的自动化测试,验证应用程序的功能和性能。

二、实验原理、实验平台条件

   实验原理

           Selenium自动化测试是一种软件测试方法,它使用自动化脚本模拟用户与Web应用程序的交互。这种方法可以显著提高测试效率,减少人为错误,并允许测试人员覆盖更广泛的测试场景。

     1. Selenium WebDriver

          Selenium的核心是WebDriver,这是一个API,提供了一种编程接口来控制Web浏览器的行为。WebDriver可以启动浏览器,导航到Web页面,与页面元素交互,并验证页面状态。

     2. 定位策略

          Selenium使用不同的策略来定位页面元素,这些策略包括:

                            ID:通过元素的ID属性进行定位。

                            Name:通过元素的Name属性进行定位。

                            Class Name:通过元素的Class属性进行定位。

                            XPath:使用XPath表达式来定位页面上的元素。

                            CSS Selector:使用CSS选择器来定位元素。

     3. 交互操作

           自动化脚本可以通过Selenium WebDriver执行各种用户交互操作,例如:

                            点击:模拟鼠标点击事件。

                            输入:在输入框中输入文本。

                            键盘操作:使用键盘快捷键进行操作,如使用Keys.ENTER模拟回车键。

     4. 等待机制

        由于Web应用程序的异步特性,自动化测试脚本需要等待页面元素加载完成。Selenium提供了两种等待机制:

              隐式等待:设置一个全局的等待时间,Selenium会在尝试任何操作前等待指定的时间。

              显式等待:使用WebDriverWait和expected_conditions来编写更灵活的等待逻辑。

     5. 断言验证

               自动化测试的一个重要方面是验证应用程序的行为是否符合预期。Selenium允许使用断言来检查页面元素的文本、属性、状态等是否符合测试预期。

     6. 异常处理

          在自动化测试过程中,可能会遇到各种异常情况,如元素未找到、操作失败等。Selenium提供了异常处理机制,允许测试脚本捕获并处理这些异常。

实验平台条件

                            操作系统:Windows 11

                            编程语言:Python

                            浏览器:Chrome

                            测试工具:Selenium WebDriver

                            测试环境:Ⅰ.项目层:vscode 1.90.2+ node.js 20.9.0 +vue

                                              Ⅱ.测试层:python 3.12.4+pycharm 2024.1.3+

                                                        selenium+ chrome 126.0.6478.63 +

                                                        chrome driver


三、 实验步骤与对应结果分析  

(一)实验前提

    1.安装Python环境(python+pycharm)

     保证之前没有python文件/卸载干净

     

     如果残留,则安装新python的时候出问题:不能勾选

     

     参考教程:

        python 安装时 install for allusers 无法选择_install launcher for all users无法勾选-CSDN博客

        新建一个文件夹

        

        安装python

        官网下载

        https://www.python.org/

                

        打开文件

        

                选第二个

        

        确认全勾选

        

        必勾选1-5,后面两个可以不选

        然后browse选择一开始新建的文件夹

        

        点击install

        

        

        Python安装好之后

        Win+R 输入cmd唤出命令行

        Pip 弹出结果即python安装成功

        

        新建一个文件夹

        

        
        安装pycharm

        官网https://www.jetbrains.com/pycharm/

        点击download

        

                点击download

        

        

        下载好了 打开文件

        选择刚刚建好的文件夹

        

        全勾选

        

        点击安装

        

        点击完成

        

        出现

        

        完成

        编辑环境变量

        

        检查

        

        Pycharm激活(使用网上找的激活包就行)

        

        下载激活包

        解压 点击

        

        弹出

        

        此时能顺利打开pycharm

2.安装Selenium库

win+R键打开 cmd命令行输入

pip install selenium -i Simple Index

安装客户端库

pip install selenium -i Simple Index

3.安装Chrome浏览器及对应版本的WebDriver

安装Chrome浏览器(如果有了就跳过)

Google Chrome 网络浏览器

安装Chrome浏览器驱动(注意是驱动driver,不是网页)

先查看浏览器版本

去下载相应的driver版本

Chrome for Testing availability

下载解压

解压里面的程序文件 chromedriver.exe 到某个目录下面,注意这个目录的路径最好是没有中文名和空格的

打开、配置环境变量(只用配置到driver的目录)

(改完环境变量 pycharm要重启才能生效)

(二)实验步骤

1.pycharm内selenium配置
  1. 打开编辑器中的setting
  2. 点击+Add Content Root
  3. 找到安装selenium的路径

pip show selenium

在pycharm填上上图显示的selenium路径

检查Pycharm默认配置路径

确定一下

2.新建python测试

                Ⅰ.选择元素

                可以使用浏览器的 开发者工具栏 帮我们查看、选择 web 元素。

                ( 比如:用chrome浏览器访问百度,按F12(ctrl+shift+I)后,点击下图箭头处的                 Elements 标签,即可查看页面对应的HTML 元素

        <input id="kw" name="wd" class="s_ipt" value="" maxlength="255" autocomplete="off">

                Ⅱ.新建python测试文件夹

                新建测试文件

                示例:gameMall.py代码

# from selenium import webdriver

# from selenium.webdriver.chrome.service import Service

#

# # 创建 WebDriver 对象,指明使用chrome浏览器驱动

# wd = webdriver.Chrome(service=Service(r'd:\chromedriver\chromedriver-win64\chromedriver.exe'))

#

# # 调用WebDriver 对象的get方法 可以让浏览器打开指定网址

# wd.get('http://localhost:5173/')

#

# # 程序运行完会自动关闭浏览器,就是很多人说的闪退

# # 这里加入等待用户输入,防止闪退

# input('等待回车键结束程序')

from selenium import webdriver

from selenium.webdriver.chrome.service import Service

from selenium.webdriver.common.keys import Keys

from selenium.webdriver.common.by import By

from time import sleep

# 创建 WebDriver 对象,指明使用chrome浏览器驱动

wd = webdriver.Chrome(service=Service(r'd:\chromedriver\chromedriver-win64\chromedriver.exe'))

try:

    # 打开页面

    wd.get('http://localhost:5173/page1')

    # 等待页面加载完成,可能需要一些时间

    sleep(3)

    # 输入用户名

    userNameInput = wd.find_element(By.XPATH, '//input[@placeholder="输入你的用户名(选填)"]')

    userNameInput.send_keys('自动化测试用户')

    # 输入评论

    commentInput = wd.find_element(By.XPATH, '//textarea[@placeholder="写下你的评论..."]')

    commentInput.send_keys('这是一个自动化测试的评论。')

    # 提交评论

    submitButton = wd.find_element(By.XPATH, '//button[text()="提交评论"]')

    submitButton.click()

    # 等待评论显示,可能需要一些时间

    sleep(2)

    # 验证评论是否成功添加,这里需要根据实际页面元素的定位调整

    # 例如,检查最新的评论是否包含我们输入的内容

    comments = wd.find_elements(By.CLASS_NAME, 'comment-text')

    last_comment = comments[-1]  # 假设最新评论是列表中的最后一个元素

    assert '这是一个自动化测试的评论。' in last_comment.text

finally:

    # 关闭浏览器

    # wd.quit()

    # 等待用户输入,防止脚本结束后浏览器关闭

    input('自动化测试完成,按回车键关闭浏览器...')

四、实验结果分析

  • 结果分析

通过执行gameMall.py脚本,成功实现了自动化测试流程。脚本首先打开指定的Web页面,然后模拟用户输入用户名和评论,提交评论后,脚本等待页面加载并验证评论是否成功添加。在测试过程中,通过断言检查评论内容是否正确显示,确保了测试的有效性。

  • 重点问题及解答

如何确保测试脚本的稳定性和可靠性?

通过显式等待和隐式等待机制,确保页面元素加载完成,避免因元素未加载而导致的测试失败。

五、 实验总结

        通过本次实验,我深入理解了Selenium自动化测试的原理和实践方法。实验过程中,学习了如何配置测试环境、编写测试脚本、定位页面元素以及验证测试结果。通过实际的自动化测试案例,体会到了自动化测试在提高测试效率和准确性方面的优势。

六、 附件

被测试的项目gameMall部分源码:

Router层(index.js):

import { createRouter, createWebHistory } from 'vue-router';

import Home from '../views/home.vue';

import Page1 from '../views/page1.vue';

import Page2 from '../views/page2.vue';

import Page3 from '../views/page3.vue';

import Page4 from '../views/page4.vue';

import Welcome from '../views/welcome.vue';

const routes = [

  {

    path: '/', // 根路由指向欢迎页面

    name: 'Welcome',

    component: Welcome

  },

  {

    path: '/page1',

    name: 'Page1',

    component: Page1

  },

  {

    path: '/page2',

    name: 'Page2',

    component: Page2

  },

  {

    path: '/page3',

    name: 'Page3',

    component: Page3

  },

  {

    path: '/page4',

    name: 'Page4',

    component: Page4

  },

  {

    path: '/home',

    name: 'home',

    component: Home

  }

];

const router = createRouter({

  history: createWebHistory(),

  routes

});

export default router;

Views层(page1.vue):

<template>

  <div class="page1">

    <div class="header">

      <h1>页面 1</h1>

    </div>

    <div class="content">

      <h2>(测试评论)</h2>

      <p>评论区不是无人区!请友善发言哇!</p>

      <p>评论区不是无人区!请友善发言哇!</p>

      <!-- 评论区域 -->

      <div class="comments">

        <h3>用户评论</h3>

        <div class="comment" v-for="(comment, index) in comments" :key="index">

          <p class="comment-user">{{ comment.user }}</p>

          <p class="comment-text">{{ comment.text }}</p>

        </div>

        <div class="new-comment">

          <!-- 添加了一个输入框用于用户输入自己的名字,如果没有输入则默认为“路人” -->

          <input v-model="userName" placeholder="输入你的用户名(选填)" />

          <textarea v-model="newCommentText" placeholder="写下你的评论..."></textarea>

          <button @click="addComment">提交评论</button>

        </div>

      </div>

    </div>

    <div class="footer">

      <p>版权所有 © 2024 GameMall</p>

    </div>

  </div>

</template>

<script>

export default {

  name: 'Page1',

  data() {

    return {

      comments: [

        { user: '用户A', text: '这是一个很棒的游戏!' },

        { user: '用户B', text: '游戏画面很精美。' }

      ],

      newCommentText: '',

      userName: '' // 用户输入的名字

    };

  },

  methods: {

    addComment() {

      if (this.newCommentText.trim() === '') {

        alert('评论内容不能为空!');

        return;

      }

      const user = this.userName.trim() || '路人'; // 如果userName为空,则默认用户名为“路人”

      this.comments.push({

        user,

        text: this.newCommentText

      });

      this.newCommentText = ''; // 清空评论输入框

      this.userName = ''; // 清空用户名输入框

    }

  }

};

</script>

<style scoped>

/* 页面整体样式 */

.page1 {

  display: flex;

  flex-direction: column;

  align-items: center;

  justify-content: flex-start;

  min-height: 100vh;

  background-color: #f9f9f9;

}

.header {

  background-color: #0973c4;

  color: #ffffff;

  padding: 20px;

  text-align: center;

}

.header h1 {

  margin: 0;

  font-size: 2em;

}

.content {

  flex: 1;

  width: 80%;

  padding: 40px 0;

  text-align: center;

}

.content h2 {

  margin-top: 0;

  font-size: 1.5em;

  color: #333;

}

.content p {

  font-size: 1em;

  color: #555;

}

.footer {

  background-color: #333;

  color: #ffffff;

  text-align: center;

  padding: 10px;

  width: 100%;

}

@media (max-width: 768px) {

  .header h1, .content h2 {

    font-size: 1.5em;

  }

  .content p {

    font-size: 0.9em;

  }

}

/* 评论区域样式 */

.comments {

  width: 100%;

  margin-top: 20px;

  padding: 10px;

  background-color: #fff;

  border-radius: 8px;

  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);

}

.comment {

  padding: 10px;

  border-bottom: 1px solid #eee;

}

.comment-user {

  font-weight: bold;

}

.comment-text {

  margin-top: 5px;

}

.new-comment {

  margin-top: 10px;

}

.new-comment textarea {

  width: 100%;

  padding: 8px;

  border: 1px solid #ddd;

  border-radius: 4px;

  resize: vertical;

}

.new-comment button {

  margin-left: 10px;

  padding: 8px 16px;

  border: none;

  border-radius: 4px;

  background-color: #0973c4;

  color: white;

  cursor: pointer;

}

.new-comment button:hover {

  background-color: #0c58a6;

}

</style>

App.vue:

<template>

  <div class="game-ad">

    <!-- 左侧导航栏 -->

      <!-- 左侧导航栏 -->

      <nav class="sidebar">

          <h3>菜单</h3>

          <router-link to="/home" class="sidebar-link">首页</router-link>

          <router-link to="/page1" class="sidebar-link">页面1</router-link>

          <router-link to="/page2" class="sidebar-link">页面2</router-link>

          <router-link to="/page3" class="sidebar-link">页面3</router-link>

          <router-link to="/page4" class="sidebar-link">页面4</router-link>

        </nav>

   

    <!-- 右侧内容区域使用 <router-view> 来显示当前路由的组件 -->

    <div class="content">

      <router-view></router-view>

    </div>

  </div>

</template>

<script>

export default {

  data() {

    return {

      games: [

        {

          title: '赛尔达传说(The Legend of Zelda Ⅰ)',

          image: '/images/shop_banner3.jpg',

          description: '一款经典的冒险游戏...'

        },

        {

          title: '饼豆人(Candy Crush)',

          image: '/images/shop_banner2.jpg',

          description: '一款休闲益智游戏...'

        },

        {

          title: '超级牛里奥兄弟(Super Mario Bros.)',

          image: '/images/shop_banner1.jpg',

          description: '任天堂经典游戏系列之一...'

        }

      ],

      currentPromotion: {

        title: '赛尔达传说(The Legend of Zelda Ⅰ)',

        image: '/images/shop_banner3.jpg',

        originalPrice: '$58.8',

        currentPrice: '$30.0'

      },

      currentIndex: 0

    };

  },

  methods: {

    changePromotion() {

      this.currentIndex = (this.currentIndex + 1) % this.games.length;

      this.currentPromotion = this.games[this.currentIndex];

    }

  }

};

</script>

<style scoped>

/* 在这里添加CSS样式 */

/* 更新CSS样式以实现左右布局 */

.game-ad {

  display: flex; /* 使用Flexbox布局整个页面 */

}

.layout {

  width: 100%;

  flex-direction: row; /* 设置Flexbox为行布局 */

}

.sidebar {

  flex: 1; /* 导航栏占据较小的空间 */

  background-color: #333; /* 导航栏背景颜色 */

  color: white;

  padding: 20px;

  height: 100vh; /* 导航栏高度占满视口高度 */

  position: fixed; /* 导航栏固定在页面左侧 */

  overflow-y: auto; /* 允许垂直滚动 */

}

.sidebar-link {

  color: white;

  text-decoration: none;

  display: block;

  margin: 10px 0;

  padding: 5px 0;

}

.sidebar-link:hover {

  text-decoration: underline;

}

.content {

  flex: 3; /* 内容区域占据较大的空间 */

  padding: 20px;

  margin-left: 200px; /* 为左侧导航栏留出空间 */

  background-image: url("/images/pic_background_Products.png");

  background-size: cover;

  background-position: center;

}

.header, .footer {

  background-color: #0973c4;

  color: #fff;

  text-align: center;

  padding: 20px;

}

.header h1 {

  font-size: 45px;

}

.content {

  padding: 20px;

  background-image: url("/images/pic_background_Products.png");

  background-size: cover;

  background-position: center;

}

.separator {

  width: 100%;

  border-bottom: 1px solid #f9ef2d;

  margin: 10px 0;

}

.advertisement {

  font-size: 50px;

  color: #ffffff;

  margin-bottom: 20px;

  border-bottom: 2px solid #ffffff;

  font-weight: bold;

}

.game-items {

  display: flex;

  justify-content: space-between;

}

.game-item {

  display: inline-block;

  margin: 10px;

  width: 30%;

  text-align: left;

}

.game-image {

  width: 100%;

  height: 200px; /* 根据需要调整高度 */

  background-size: cover;

  background-position: center;

  margin-bottom: 10px;

}

.game-title {

  color: #0973c4;

  font-size: 18px;

  font-weight: bold;

}

.game-description {

  color: #555;

  font-weight: bold;

}

.promotion {

  margin-top: 20px;

  text-align: center;

}

.promotion-image {

  width: 50%;

  height: auto;

  margin-bottom: 20px;

}

.promotion-title, .current-price, .promotion-price {

  color: #555;

  font-weight: bold;

}

.promotion-button {

  background-color: #0973c4;

  color: #fff;

  border: none;

  padding: 5px 10px;

  border-radius: 5px;

  cursor: pointer;

}

.footer p {

  padding: 10px;

}

</style>

写在后面

        *老师推荐了白夜黑羽的b站教程,可以搜名字,讲得很详细,后续也有更深一步的测试。

        *改自以前的实验报告,可能存在编写错误/引用问题,私信会滑跪。

        *仅写来纪念爱过的日子。

您可能感兴趣的与本文相关的镜像

Python3.8

Python3.8

Conda
Python

Python 是一种高级、解释型、通用的编程语言,以其简洁易读的语法而闻名,适用于广泛的应用,包括Web开发、数据分析、人工智能和自动化脚本

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值