selenium+python环境的搭建的自动化测试

一、安装python:
我安装的是2.7.13版本的;可以在CMD下 运行python命令查看是否安装python,以及安装版本;

https://www.python.org/getit/这个地址可以下装所需版本。
安装完成后需要配置环境变量,path=……;python的安装目录

二、setuptool安装(python 的基础包工具)

http://pypi.python.org/pypi/setuptools 这个是下载路径,一开始我也下载了,但是装得一塌糊涂。后来网上找到一篇教程,是直接通过直接python脚本自动完成setuptool的下载和安装。默认会找到 python 的安装路径,将安装到 Python 安装目录下的lib下的 site-package下 如D:\Python27\Lib\site-packages 目录下

脚本如下:(复制进xx.py文件里 保存 运行py文件即可)

#!usr/bin/python
#!/usr/bin/env python

"""
Setuptools bootstrapping installer.

Maintained at https://github.com/pypa/setuptools/tree/bootstrap.

Run this script to install or upgrade setuptools.

This method is DEPRECATED. Check https://github.com/pypa/setuptools/issues/581 for more details.
"""

import os
import shutil
import sys
import tempfile
import zipfile
import optparse
import subprocess
import platform
import textwrap
import contextlib

from distutils import log

try:
    from urllib.request import urlopen
except ImportError:
    from urllib2 import urlopen

try:
    from site import USER_SITE
except ImportError:
    USER_SITE = None

# 33.1.1 is the last version that supports setuptools self upgrade/installation.
DEFAULT_VERSION = "33.1.1"
DEFAULT_URL = "https://pypi.io/packages/source/s/setuptools/"
DEFAULT_SAVE_DIR = os.curdir
DEFAULT_DEPRECATION_MESSAGE = "ez_setup.py is deprecated and when using it setuptools will be pinned to {0} since it‘s the last version that supports setuptools self upgrade/installation, check https://github.com/pypa/setuptools/issues/581 for more info; use pip to install setuptools"

MEANINGFUL_INVALID_ZIP_ERR_MSG = ‘Maybe {0} is corrupted, delete it and try again.‘

log.warn(DEFAULT_DEPRECATION_MESSAGE.format(DEFAULT_VERSION))

def _python_cmd(*args):
    """
    Execute a command.

    Return True if the command succeeded.
    """
    args = (sys.executable,) + args
    return subprocess.call(args) == 0

def _install(archive_filename, install_args=()):
    """Install Setuptools."""
    with archive_context(archive_filename):
        # installing
        log.warn(‘Installing Setuptools‘)
        if not _python_cmd(‘setup.py‘, ‘install‘, *install_args):
            log.warn(‘Something went wrong during the installation.‘)
            log.warn(‘See the error message above.‘)
            # exitcode will be 2
            return 2

def _build_egg(egg, archive_filename, to_dir):
    """Build Setuptools egg."""
    with archive_context(archive_filename):
        # building an egg
        log.warn(‘Building a Setuptools egg in %s‘, to_dir)
        _python_cmd(‘setup.py‘, ‘-q‘, ‘bdist_egg‘, ‘--dist-dir‘, to_dir)
    # returning the result
    log.warn(egg)
    if not os.path.exists(egg):
        raise IOError(‘Could not build the egg.‘)

class ContextualZipFile(zipfile.ZipFile):

    """Supplement ZipFile class to support context manager for Python 2.6."""

    def __enter__(self):
        return self

    def __exit__(self, type, value, traceback):
        self.close()

    def __new__(cls, *args, **kwargs):
        """Construct a ZipFile or ContextualZipFile as appropriate."""
        if hasattr(zipfile.ZipFile, ‘__exit__‘):
            return zipfile.ZipFile(*args, **kwargs)
        return super(ContextualZipFile, cls).__new__(cls)

@contextlib.contextmanager
def archive_context(filename):
    """
    Unzip filename to a temporary directory, set to the cwd.

    The unzipped target is cleaned up after.
    """
    tmpdir = tempfile.mkdtemp()
    log.warn(‘Extracting in %s‘, tmpdir)
    old_wd = os.getcwd()
    try:
        os.chdir(tmpdir)
        try:
            with ContextualZipFile(filename) as archive:
                archive.extractall()
        except zipfile.BadZipfile as err:
            if not err.args:
                err.args = (‘‘, )
            err.args = err.args + (
                MEANINGFUL_INVALID_ZIP_ERR_MSG.format(filename),
            )
            raise

        # going in the directory
        subdir = os.path.join(tmpdir, os.listdir(tmpdir)[0])
        os.chdir(subdir)
        log.warn(‘Now working in %s‘, subdir)
        yield

    finally:
        os.chdir(old_wd)
        shutil.rmtree(tmpdir)

def _do_download(version, download_base, to_dir, download_delay):
    """Download Setuptools."""
    py_desig = ‘py{sys.version_info[0]}.{sys.version_info[1]}‘.format(sys=sys)
    tp = ‘setuptools-{version}-{py_desig}.egg‘
    egg = os.path.join(to_dir, tp.format(**locals()))
    if not os.path.exists(egg):
        archive = download_setuptools(version, download_base,
            to_dir, download_delay)
        _build_egg(egg, archive, to_dir)
    sys.path.insert(0, egg)

    # Remove previously-imported pkg_resources if present (see
    # https://bitbucket.org/pypa/setuptools/pull-request/7/ for details).
    if ‘pkg_resources‘ in sys.modules:
        _unload_pkg_resources()

    import setuptools
    setuptools.bootstrap_install_from = egg

def use_setuptools(
        version=DEFAULT_VERSION, download_base=DEFAULT_URL,
        to_dir=DEFAULT_SAVE_DIR, download_delay=15):
    """
    Ensure that a setuptools version is installed.

    Return None. Raise SystemExit if the requested version
    or later cannot be installed.
    """
    to_dir = os.path.abspath(to_dir)

    # prior to importing, capture the module state for
    # representative modules.
    rep_modules = ‘pkg_resources‘, ‘setuptools‘
    imported = set(sys.modules).intersection(rep_modules)

    try:
        import pkg_resources
        pkg_resources.require("setuptools>=" + version)
        # a suitable version is already installed
        return
    except ImportError:
        # pkg_resources not available; setuptools is not installed; download
        pass
    except pkg_resources.DistributionNotFound:
        # no version of setuptools was found; allow download
        pass
    except pkg_resources.VersionConflict as VC_err:
        if imported:
            _conflict_bail(VC_err, version)

        # otherwise, unload pkg_resources to allow the downloaded version to
        #  take precedence.
        del pkg_resources
        _unload_pkg_resources()

    return _do_download(version, download_base, to_dir, download_delay)

def _conflict_bail(VC_err, version):
    """
    Setuptools was imported prior to invocation, so it is
    unsafe to unload it. Bail out.
    """
    conflict_tmpl = textwrap.dedent("""
        The required version of setuptools (>={version}) is not available,
        and can‘t be installed while this script is running. Please
        install a more recent version first, using
        ‘easy_install -U setuptools‘.

        (Currently using {VC_err.args[0]!r})
        """)
    msg = conflict_tmpl.format(**locals())
    sys.stderr.write(msg)
    sys.exit(2)

def _unload_pkg_resources():
    sys.meta_path = [
        importer
        for importer in sys.meta_path
        if importer.__class__.__module__ != ‘pkg_resources.extern‘
    ]
    del_modules = [
        name for name in sys.modules
        if name.startswith(‘pkg_resources‘)
    ]
    for mod_name in del_modules:
        del sys.modules[mod_name]

def _clean_check(cmd, target):
    """
    Run the command to download target.

    If the command fails, clean up before re-raising the error.
    """
    try:
        subprocess.check_call(cmd)
    except subprocess.CalledProcessError:
        if os.access(target, os.F_OK):
            os.unlink(target)
        raise

def download_file_powershell(url, target):
    """
    Download the file at url to target using Powershell.

    Powershell will validate trust.
    Raise an exception if the command cannot complete.
    """
    target = os.path.abspath(target)
    ps_cmd = (
        "[System.Net.WebRequest]::DefaultWebProxy.Credentials = "
        "[System.Net.CredentialCache]::DefaultCredentials; "
        ‘(new-object System.Net.WebClient).DownloadFile("%(url)s", "%(target)s")‘
        % locals()
    )
    cmd = [
        ‘powershell‘,
        ‘-Command‘,
        ps_cmd,
    ]
    _clean_check(cmd, target)

def has_powershell():
    """Determine if Powershell is available."""
    if platform.system() != ‘Windows‘:
        return False
    cmd = [‘powershell‘, ‘-Command‘, ‘echo test‘]
    with open(os.path.devnull, ‘wb‘) as devnull:
        try:
            subprocess.check_call(cmd, stdout=devnull, stderr=devnull)
        except Exception:
            return False
    return True
download_file_powershell.viable = has_powershell

def download_file_curl(url, target):
    cmd = [‘curl‘, url, ‘--location‘, ‘--silent‘, ‘--output‘, target]
    _clean_check(cmd, target)

def has_curl():
    cmd = [‘curl‘, ‘--version‘]
    with open(os.path.devnull, ‘wb‘) as devnull:
        try:
            subprocess.check_call(cmd, stdout=devnull, stderr=devnull)
        except Exception:
            return False
    return True
download_file_curl.viable = has_curl

def download_file_wget(url, target):
    cmd = [‘wget‘, url, ‘--quiet‘, ‘--output-document‘, target]
    _clean_check(cmd, target)

def has_wget():
    cmd = [‘wget‘, ‘--version‘]
    with open(os.path.devnull, ‘wb‘) as devnull:
        try:
            subprocess.check_call(cmd, stdout=devnull, stderr=devnull)
        except Exception:
            return False
    return True
download_file_wget.viable = has_wget

def download_file_insecure(url, target):
    """Use Python to download the file, without connection authentication."""
    src = urlopen(url)
    try:
        # Read all the data in one block.
        data = src.read()
    finally:
        src.close()

    # Write all the data in one block to avoid creating a partial file.
    with open(target, "wb") as dst:
        dst.write(data)
download_file_insecure.viable = lambda: True

def get_best_downloader():
    downloaders = (
        download_file_powershell,
        download_file_curl,
        download_file_wget,
        download_file_insecure,
    )
    viable_downloaders = (dl for dl in downloaders if dl.viable())
    return next(viable_downloaders, None)

def download_setuptools(
        version=DEFAULT_VERSION, download_base=DEFAULT_URL,
        to_dir=DEFAULT_SAVE_DIR, delay=15,
        downloader_factory=get_best_downloader):
    """
    Download setuptools from a specified location and return its filename.

    `version` should be a valid setuptools version number that is available
    as an sdist for download under the `download_base` URL (which should end
    with a ‘/‘). `to_dir` is the directory where the egg will be downloaded.
    `delay` is the number of seconds to pause before an actual download
    attempt.

    ``downloader_factory`` should be a function taking no arguments and
    returning a function for downloading a URL to a target.
    """
    # making sure we use the absolute path
    to_dir = os.path.abspath(to_dir)
    zip_name = "setuptools-%s.zip" % version
    url = download_base + zip_name
    saveto = os.path.join(to_dir, zip_name)
    if not os.path.exists(saveto):  # Avoid repeated downloads
        log.warn("Downloading %s", url)
        downloader = downloader_factory()
        downloader(url, saveto)
    return os.path.realpath(saveto)

def _build_install_args(options):
    """
    Build the arguments to ‘python setup.py install‘ on the setuptools package.

    Returns list of command line arguments.
    """
    return [‘--user‘] if options.user_install else []

def _parse_args():
    """Parse the command line for options."""
    parser = optparse.OptionParser()
    parser.add_option(
        ‘--user‘, dest=‘user_install‘, action=‘store_true‘, default=False,
        help=‘install in user site package‘)
    parser.add_option(
        ‘--download-base‘, dest=‘download_base‘, metavar="URL",
        default=DEFAULT_URL,
        help=‘alternative URL from where to download the setuptools package‘)
    parser.add_option(
        ‘--insecure‘, dest=‘downloader_factory‘, action=‘store_const‘,
        const=lambda: download_file_insecure, default=get_best_downloader,
        help=‘Use internal, non-validating downloader‘
    )
    parser.add_option(
        ‘--version‘, help="Specify which version to download",
        default=DEFAULT_VERSION,
    )
    parser.add_option(
        ‘--to-dir‘,
        help="Directory to save (and re-use) package",
        default=DEFAULT_SAVE_DIR,
    )
    options, args = parser.parse_args()
    # positional arguments are ignored
    return options

def _download_args(options):
    """Return args for download_setuptools function from cmdline args."""
    return dict(
        version=options.version,
        download_base=options.download_base,
        downloader_factory=options.downloader_factory,
        to_dir=options.to_dir,
    )

def main():
    """Install or upgrade setuptools and EasyInstall."""
    options = _parse_args()
    archive = download_setuptools(**_download_args(options))
    return _install(archive, _build_install_args(options))

if __name__ == ‘__main__‘:
    sys.exit(main())

三、pip的安装(python 的安装包管理工具)

下载地址:https://pypi.python.org/pypi/pip

是一个压缩包,解压后 shift+鼠标右击,选择在此处打开命令窗口  然后执行python setup.py install;接着,再切换到 python的安装目录下的scripts下如D:\Python27\Scripts ,在此处打开命令窗口 执行  easy_install pip

四、selenium安装  在python安装目录下的Scripts目录下 打开DOS命令窗口 输入 pip install -U selenium (该方式在联网的情况下 自动进行下载和安装)

五、下载 selenium 的服务端(https://code.google.com/p/selenium/) 找到selenium-server-standalone-XXX.jar

下载下来后解压;在 selenium-server-standalone-xxx.jar 目 录 下打开dos命令窗口, 使 用 命 令 java -jarselenium-server-standalone-xxx.jar 启动(如果打不开,查看是否端口被占 用:netstat -aon|findstr 4444)。

插入题外话:我安装到这里的时候,以为已经完成环境的部署了,装了这么多但是完全不知道怎么用,除了一堆不知道的安装后的文件,我什么也没见着,一脸懵,中午吃饭的时候,给一位开发的同事吐槽了下,他刚好了解,吃好饭后他就帮我接着部署。

1、先是检查了我的python是否安装且配置环境变量 (其他的没检查,估计用不到? 我不太清楚)

2、接着因为我使用的是Firefox浏览器,说是版本太高,selenium版本不支持,然后卸载了50.几版本的Firefox浏览器,取了个46.几版本的;接着在附件组件下的插件出下载了

firebug 和firepath  是自动化测试脚本开发调试中用到

3、安装PyCharm,是由JetBrains打造的一款Python IDE

写了段代码验证

# coding = utf-8
from selenium import webdriver
browser = webdriver.Firefox()
browser.get("http://www.baidu.com")
browser.find_element_by_id("kw").send_keys("输入框查询内容")
browser.find_element_by_id("su").click()
browser.quit()

但是报错 没有 geckodriver.exe 缺少对应浏览器driver驱动

4、取到 对应driver ,Firefox取 geckodriver.exe  放到 Windows: python安装根目录(与python.exe 同一目录)注:其实放在哪里都行,只要能被找到就行,放到其他目录时,就加上配置环境变量path值,以让程序找到

然后在执行上面python代码,执行成功

至此,selenium+python的环境部署成功,可以开始进行自动化测试脚本编写

时间: 2024-11-07 11:56:05

selenium+python环境的搭建的自动化测试的相关文章

Python 语言搭建SELENIUM测试环境,搭建过程记录。

第一步,安装Python: 第二步,安装SetupTools: 第三步,安装Pip: 第四步,安装selenium(for python) 第五步,新建第一个基于Firefox的测试用例 上述 只是步骤,具体内容,明天补充,睡觉 咯--- Python 语言搭建SELENIUM测试环境,搭建过程记录.

Python环境重新搭建

1.下载python 官网下载最新版python http://www.wingide.com/downloads 2.下载PyCharm 官网可下载最新版pyCharm-professional http://www.jetbrains.com/pycharm/download/ 实际学习中,未使用该版本,从同事那里拷贝了pyCharm2.7.3,下面提供给大家下载方式,需要的可以自行下载. 3.破解pyCharm2.7.3 安装python2.7.5后,安装pyCharm2.7.3,首次登陆

selenium+python 环境搭建(windows)

用的selenium2.0 selenium2.0=selenium1.0+WebDriver 安装: 1.下载.安装python,我使用的是python3.3.2 2.配置环境变量Path,在字符串末尾加一个分号 ";",然后输入python的安装路径 设置好环境变量后,在cmd里面输入python会看到 Python 3.3.2 (v3.3.2:d047928ae3f6, May 16 2013, 00:06:53) [MSC v.1600 64 bit (AMD64)] on w

selenium python 环境搭建(64位 windows)

之前写了同样的文章,可是后来自己按照给文章再次搭建环境当搭建环境成功后却发现还是无法用.使用from selenium import webdriver,在run的时候却出现ImportError: cannot import name webdriver的提示,但是在Python IDLE里面跑却没有错误,在网上找了很多资料说在控制太中使用import selenium print selenium.__file__去看打印出的文件路径,如果不是下面类似的C:\Python27\lib\sit

Windows下Python环境的搭建

我刚开始接触Python没多久,当然这也是为初学者来更好的去入门Python,我电脑上既跑着Windows也跑着Red Hat的Linux,相比较而言,开发我还是更青睐于Linux系统,很多开发工具红帽公司都给提供了. 那么这里我们先说一下Linux下的Python,Linux下Red Hat在光盘里集成了很多套的开发工具,当我们在安装Linux之前选择安装系统类型的时候我们选择GUI,然后把相应的开发工具勾选上就好啦,我当时勾选上了开发工具,现在电脑上既有JDK,也由于GCC,也有Python

windows系统下Python环境的搭建

1.首先访问http://www.python.org/download/去下载最新的python版本. 2.安装下载包,一路next. 3.为计算机添加安装目录搭到环境变量,如图把python的安装目录添加到pth系统变量中即可. 4.测试python安装是否成功,cmd打开命令行输入 python 命令,如下图即成功了 5.Hello World! 按照很多资料上写的,输入 print 'Hello World!' 居然是不成功,说语法错误!这是一个坑了,很多资料是都是python 1.*/

Windows 64 位系统下 Python 环境的搭建

Windows 64 位开发环境 注意:本教程适用于 Windows 7 64 位操作系统 及 Windows 10 64 位操作系统,其他系统尚未经过校验. 安装 IDE PyCharm 下载:https://www.jetbrains.com/pycharm/ 安装 Python 环境 Python2.7 下载:https://www.python.org/downloads/ Python2.7 的默认安装目录在 C:/Python27/,安装目录请勿转移到其他盘!有C盘洁癖症的患者请特别

Linux下python环境的搭建

一.安装linux最小化系统(CentOS6) 安装最小系统即可 二.安装pyenv多版本管理工具 (一)pyenv的安装步骤 1.安装git yum install git -y 2.安装python编译所需要用到的包 yum -y install gcc make patch gdbm-devel openssl-devel sqlite-devel readline-devel zlib-devel bzip2-devel 3.创建python用户 useradd python 给pyth

自动化测试(Selenium+python)-环境搭建

一.Python安装(win7 64位系统) 1.下载Python安装包,选择2.7版本和3.6版本都可以 官网下载地址:https://www.python.org/62 2.Python安装,双击傻瓜式安装到D盘(建议别安装在c盘) 二.环境变量 1.安装完成后,看下这个目录D:\python\Scripts,有没pip.exe和easy_install.exe(一般都有) 2.将D:\python和D:\python\Scripts,添加到环境变量path下 三.安装selenium 1.