你的位置:首页 > 信息动态 > 新闻中心
信息动态
联系我们

Web自动化——selenium自动化环境搭建以及脚本编写基本步骤(基于Python)

2021/12/19 15:48:29

1 环境搭建

step1: 安装Python环境

  • (1)安装Python安装包:Python官网下载Python直接安装,官网下载地址:https://www.python.org/downloads/
  • (2)安装Python可视化环境,如PyCharm,PyCharm下载地址:https://www.jetbrains.com/pycharm/download/#section=mac

step2: 安装selenium包

Selenium WebDriver是一个第三方模块,并不是Python的标准模块,所以在导入这个模块之前,还需要将这个第三方模块安装到Python的目录中,这样才能使用import或者from…import语句进行导入。

step2.1 通过pip包管理工具安装:

pip是一个通用的 Python 包管理工具,提供了对 Python 包的查找、下载、安装、卸载的功能

  • (1) 安装selenium

    • 1)安装最新版本: pip install selenium
    • 2)安装指定版本:pip install selenium==版本号,查看可安装的版本号:pip install selenium==随便输入错误的版本号
  • (2)查看selenium
    pip show selenium

  • (3)卸载selenium
    pip uninstall selenium

step3: 安装浏览器

step4: 安装浏览器驱动

  • (1)下载浏览器驱动,各个驱动下载地址: https://www.selenium.dev/documentation/webdriver/getting_started/install_drivers/

    • 浏览器版本必须和驱动版本一致!
      • 火狐:
        1)Firefox 48 以上版本: selenium 3.x + Firefox驱动(geckodriver);
        2)Firefox 48 以下版本:selenium 2.x + 内置驱动

      • 谷歌: selenium 2.x/3.x + Chrome驱动(chromedriver);

      • Edge: selenium 3.x + Edge驱动(MicrosoftWebDriver);

  • (2)把驱动文件所在目录添加到Path环境变量中,或直接放到Python安装目录,因为Python已添加到Path中

    • 环境变量:指定系统搜索的目录。terminal终端命令界面中输入命令,默认搜索的顺序为:检测是否为内部命令->检测是否为当前目录下的可执行文件->检测环境变量指定的目录。

2. web自动化测试脚本编写的基本步骤

step1:导入Selenium WebDriver模块

from selenium import webdriver

step2: 创建驱动浏览器对象并启动浏览器

浏览器驱动对象 = webdriver.Firefox()
浏览器驱动对象 = webdriver.Chrome()
浏览器驱动对象 = webdriver.Edge()

step3: 编写自动化执行步骤

如:打开网页:浏览器驱动对象.get("网页链接")
浏览器窗口最大化:driver.maxmimize()

step4: 关闭驱动对象

浏览器驱动对象.quit()

e.g.

# step1:导入Selenium WebDriver模块
from  selenium import webdriver
import  time

for i in range(1,10):
  #step2: 创建驱动浏览器对象并启动浏览器
  driver = webdriver.Firefox()
  #step3: 编写自动化执行步骤
  driver.maxmimize()
  driver.get("https://www.baidu.com")
  #清空文本框
  driver.find_element_by_xpath("//input[@id='su']").clear()
  # 输入内容
  driver.find_element_by_xpath("//input[@id='su']").send_keys("百度一下")
  # 点击
  driver.find_element_by_xpath("//input[@name='ss']").click()
  time.sleep(5)
  # step4: 关闭驱动对象
  driver.quit()