Selenium 学习笔记1-安装和浏览器属性配置

一、Selenium 介绍和安装

1.Selenium 介绍

Selenium 是一个用于Web应用程序测试的工具。Selenium测试直接运行在浏览器中,就像真正的用户在操作一样。支持的浏览器包括IE(7, 8, 9, 10, 11),Mozilla Firefox,Safari,Google Chrome,Opera等。这个工具的主要功能包括:测试与浏览器的兼容性——测试你的应用程序看是否能够很好得工作在不同浏览器和操作系统之上。测试系统功能——创建回归测试检验软件功能和用户需求。支持自动录制动作和自动生成 .Net、Java、Perl等不同语言的测试脚本。(比较懒,来源度娘)

2.安装

# Cmd/shell 终端输入一下命令
pip3 install selenium
# 查看版本号
pip show selenium

在这里插入图片描述
selenium 实现自动化测试的流程图
以chrome来举例

Selenium 库
webdriverServer 浏览器驱动
chromedriver Chrome浏览器驱动
chrome 浏览器实现操作

二、Chrome 浏览器驱动下载地址

1.驱动版本号要和浏览器版本号相对应:

下载地址: 谷歌浏览器驱动下载地址

2.浏览器驱动文件配置

2.1.1 window环境配置

\…\python3.X\chromedriver.exe
不知道python安装在哪里, 在cmd 输入

where python
2.1.2浏览器要停止自动更新

由于chrom要和驱动版本对应所以要把浏览器的自动更新停止掉,避免自动更新出现版本不对应
win + r 输入 msconfig
在这里插入图片描述

2.2 Mac OS 配置

下载chromedriver解压后,在解压到目录打开终端使用命令

sudo mv chromedriver /usr/local/bin  # 需要密码授权

在运行脚本时会提示不安全,在系统偏好设置-安全性和隐私-通用中,点击:仍然允许,再次执行脚本就可以

三、Selenium 基本语法

1.导入selenium模块

# 导入驱动类
from selenium import webdriver

# 参数化驱动
browser = webdriver.Chrome()
browser.get("http://www.baidu.com")

在这里插入图片描述
通过查看源码,可以看出
webdriver通过 service.start 用subprocess来执行cmd命令调用chromedriver.exe

        self.service = Service(
            executable_path,
            port=port,
            service_args=service_args,
            log_path=service_log_path)
        self.service.start()

        try:
            RemoteWebDriver.__init__(
                self,
                command_executor=ChromeRemoteConnection(
                    remote_server_addr=self.service.service_url,
                    keep_alive=keep_alive),
                desired_capabilities=desired_capabilities)
        except Exception:
            self.quit()
            raise
        self._is_remote = False
        
        
        ## start的源码,用subprocess 用cmd打开Chromedriver.exe
        def start(self):
        """
        Starts the Service.

        :Exceptions:
         - WebDriverException : Raised either when it can't start the service
           or when it can't connect to the service
        """
        try:
            cmd = [self.path]
            cmd.extend(self.command_line_args())
            self.process = subprocess.Popen(cmd, env=self.env,
                                            close_fds=platform.system() != 'Windows',
                                            stdout=self.log_file,
                                            stderr=self.log_file,
                                            stdin=PIPE)

executable_path - 可执行文件的路径。如果使用默认值,则假定可执行文件位于$PATH中。
port- 你希望服务运行的端口,如果为0,使用空闲端口。
options - 这是ChromeOptions的一个实例
service_args - 要传递给驱动程序服务的args列表
desired_capabilities -仅具有非浏览器特定功能的字典对象,例如“proxy”或“loggingPref”。
service_log_path - 记录来自驱动程序的信息存放路径。
chrome_options - chrome选项。
keep_alive -是否配置ChromeRemoteConnection使用HTTP keep-alive。
其中options和chrome_options:使用options代替chrome_options。

2.配置 Chrome 启动属性

ChromeOptions 是一个配置 chrome 启动属性的类

执行脚本之后可以看出,浏览器是自动化脚本控制的,可以通过参数控制把这个提示去掉。

# 导入驱动类
from selenium import webdriver

# 初始化浏览器驱动
# 这个用法针对Version 78 以上的谷歌浏览器才会有效
option = webdriver.ChromeOptions() 
# 去掉受自动化测试软件提示
option.add_experimental_option('useAutomationExtension', False)
option.add_experimental_option("excludeSwitches", ['enable-automation'])
# 

browser = webdriver.Chrome(chrome_options=option)
browser.get("http://www.baidu.com")

# 退出
browser.quit()

在这里插入图片描述
还有一些其他属性的配置,我用过的基本是以下这些

option.add_argument('lang=zh_CN.UTF-8')  # 设置默认编码uft-8,中文
option.add_argument('--disable-infobars')  # 禁止策略化
option.add_argument('--no-sandbox')  # 解决DevToolsActivePort文件不存在的报错
option.add_argument('window-size=1920x3000')  # 指定浏览器分辨率
option.add_argument('--disable-gpu')  # 谷歌文档提到需要加上这个属性来规避bug
option.add_argument('--incognito')  # 隐身模式(无痕模式)
option.add_argument('--start-maximized')  # 最大化运行(全屏窗口),不设置取元素会报错,也会出现点击其他元素的情况
option.add_argument('--disable-infobars')  # 禁用浏览器正在被自动化程序控制的提示
option.add_argument('--headless')  # 浏览器不提供可视化页面,也就是无头模式. linux下如果系统不支持可视化不加这条会启动失败,脚本需要在Jenkins上托管运行需要加上这个
option.binary_location = r"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe"  # 手动指定使用的浏览器位置

# 设置这两个参数就可以避免密码提示框的弹出
prefs = {}
prefs["credentials_enable_service"] = False
prefs["profile.password_manager_enabled"] = False
option.add_experimental_option("prefs", prefs)

3. selenium操作浏览器的底层实现其实是api 接口请求

** 源码

class ChromeRemoteConnection(RemoteConnection):

    def __init__(self, remote_server_addr, keep_alive=True):
        RemoteConnection.__init__(self, remote_server_addr, keep_alive)
        self._commands["launchApp"] = ('POST', '/session/$sessionId/chromium/launch_app')
        self._commands["setNetworkConditions"] = ('POST', '/session/$sessionId/chromium/network_conditions')
        self._commands["getNetworkConditions"] = ('GET', '/session/$sessionId/chromium/network_conditions')
        self._commands['executeCdpCommand'] = ('POST', '/session/$sessionId/goog/cdp/execute')

Connection用标准库urllib3封装request实现所有API接口请求,是HTTP协议api _commands的方法实现

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值