做为一名使用Selenium开发UI自动化多年的工程师,一直都对Selenium Webdriver的实现原理感受不是很清楚。怎么就经过脚本控制浏览器进行各类操做了呢?相信不少Selenium的使用者也会有相似的疑惑。最近针对这个问题看了很多了文章和书籍,在加上一点本身的思考和整理,与你们一块儿分享,一块儿学习。文章中若是有不许确的地方,但愿你们给予指正。html
想要使用Selenium实现自动化测试,主要须要三个东西。python
测试代码就是程序员利用不一样的语言和相应的selenium API库完成的代码。本文将以python为例进行说明。git
Webdriver是针对不一样的浏览器开发的,不一样的浏览器有不一样的webdriver。例如针对Chrome使用的chromedriver。程序员
浏览器和相应的Webdriver对应。github
首先咱们来看一下这三个部分的关系。
对于三个部分的关系模型,能够用一个平常生活中常见的例子来类比。web
对于打的这个行为来讲,乘客和出租车司机进行交互,告诉出租车想去的目的地,出租车司机驾驶汽车把乘客送到目的地,这样乘客就乘坐出租车到达了本身想去的地方。
这和Webdriver的实现原理是相似的,测试代码中包含了各类指望的对浏览器界面的操做,例如点击。测试代码经过给Webdriver发送指令,让Webdriver知道想要作的操做,而Webdriver根据这些操做在浏览器界面上进行控制,由此测试代码达到了在浏览器界面上操做的目的。
理清了Selenium自动化测试三个重要组成之间的关系,接下来咱们来具体分析其中一个最重要的关系。chrome
接下来我会以获取界面元素这个基本的操做为例来分析二者之间的关系。
在测试代码中,咱们第一步要作的是新建一个webdriver类的对象:json
from selenium import webdriver driver = webdriver.Chrome()
这里新建的driver
对象是一个webdriver.Chrome()
类的对象,而webdriver.Chrome()
类的本质是api
from .chrome.webdriver import WebDriver as Chrome
也就是一个来自chrome的WebDriver
类。这个.chrome.webdriver.WebDriver
是继承了selenium.webdriver.remote.webdriver.WebDriver
浏览器
from selenium.webdriver.remote.webdriver import WebDriver as RemoteWebDriver ... class WebDriver(RemoteWebDriver): """ Controls the ChromeDriver and allows you to drive the browser. You will need to download the ChromeDriver executable from http://chromedriver.storage.googleapis.com/index.html """ def __init__(self, executable_path="chromedriver", port=0, chrome_options=None, service_args=None, desired_capabilities=None, service_log_path=None): ...
以python为例,在selenium
库中,经过ID获取界面元素的方法是这样的:
from selenium import webdriver driver = webdriver.Chrome() driver.find_element_by_id(id)
find_elements_by_id
是selenium.webdriver.remote.webdriver.WebDriver
类的实例方法。在代码中,咱们直接使用的其实不是selenium.webdriver.remote.webdriver.WebDriver
这个类,而是针对各个浏览器的webdriver类,例如webdriver.Chrome()
。
因此说在测试代码中执行各类浏览器操做的方法其实都是selenium.webdriver.remote.webdriver.WebDriver
类的实例方法。
接下来咱们再深刻selenium.webdriver.remote.webdriver.WebDriver
类来看看具体是如何实现例如find_element_by_id()
的实例方法的。
经过Source code能够看到:
def find_element(self, by=By.ID, value=None): """ 'Private' method used by the find_element_by_* methods. :Usage: Use the corresponding find_element_by_* instead of this. :rtype: WebElement """ if self.w3c: ... return self.execute(Command.FIND_ELEMENT, { 'using': by, 'value': value})['value']
这个方法最后call了一个execute
方法,方法的定义以下:
def execute(self, driver_command, params=None): """ Sends a command to be executed by a command.CommandExecutor. :Args: - driver_command: The name of the command to execute as a string. - params: A dictionary of named parameters to send with the command. :Returns: The command's JSON response loaded into a dictionary object. """ if self.session_id is not None: if not params: params = {'sessionId': self.session_id} elif 'sessionId' not in params: params['sessionId'] = self.session_id params = self._wrap_value(params) response = self.command_executor.execute(driver_command, params) if response: self.error_handler.check_response(response) response['value'] = self._unwrap_value( response.get('value', None)) return response # If the server doesn't send a response, assume the command was # a success return {'success': 0, 'value': None, 'sessionId': self.session_id}
正如注释中提到的同样,其中的关键在于
response = self.command_executor.execute(driver_command, params)
一个名为command_executor
的对象执行了execute
方法。
名为command_executor
的对象是RemoteConnection
类的对象,而且这个对象是在新建selenium.webdriver.remote.webdriver.WebDriver
类对象的时候就完成赋值的self.command_executor = RemoteConnection(command_executor, keep_alive=keep_alive)
。
结合selenium.webdriver.remote.webdriver.WebDriver
类的类注释来看:
class WebDriver(object): """ Controls a browser by sending commands to a remote server. This server is expected to be running the WebDriver wire protocol as defined at https://github.com/SeleniumHQ/selenium/wiki/JsonWireProtocol :Attributes: - session_id - String ID of the browser session started and controlled by this WebDriver. - capabilities - Dictionaty of effective capabilities of this browser session as returned by the remote server. See https://github.com/SeleniumHQ/selenium/wiki/DesiredCapabilities - command_executor - remote_connection.RemoteConnection object used to execute commands. - error_handler - errorhandler.ErrorHandler object used to handle errors. """ _web_element_cls = WebElement def __init__(self, command_executor='http://127.0.0.1:4444/wd/hub', desired_capabilities=None, browser_profile=None, proxy=None, keep_alive=False, file_detector=None):
WebDriver
类的功能是经过给一个remote server发送指令来控制浏览器。而这个remote server是一个运行WebDriver wire protocol的server。而RemoteConnection
类就是负责与Remote WebDriver server的链接的类。
能够注意到有这么一个新建WebDriver
类的对象时候的参数command_executor
,默认值='http://127.0.0.1:4444/wd/hub'
。这个值表示的是访问remote server的URL。所以这个值做为了RemoteConnection
类的构造方法的参数,由于要链接remote server,URL是必须的。
如今再来看RemoteConnection
类的实例方法execute
。
def execute(self, command, params): """ Send a command to the remote server. Any path subtitutions required for the URL mapped to the command should be included in the command parameters. :Args: - command - A string specifying the command to execute. - params - A dictionary of named parameters to send with the command as its JSON payload. """ command_info = self._commands[command] assert command_info is not None, 'Unrecognised command %s' % command data = utils.dump_json(params) path = string.Template(command_info[1]).substitute(params) url = '%s%s' % (self._url, path) return self._request(command_info[0], url, body=data)
这个方法有两个参数:
command
params
command
表示指望执行的指令的名字。经过观察self._commands
这个dict
能够看到,self._commands
存储了selenium.webdriver.remote.command.Command
类里的常量指令和WebDriver wire protocol中定义的指令的对应关系。
self._commands = { Command.STATUS: ('GET', '/status'), Command.NEW_SESSION: ('POST', '/session'), Command.GET_ALL_SESSIONS: ('GET', '/sessions'), Command.QUIT: ('DELETE', '/session/$sessionId'), ... Command.FIND_ELEMENT: ('POST', '/session/$sessionId/element'),
以FIND_ELEMENT为例能够看到,指令的URL部分包含了几个组成部分:
sessionId
。Session的概念是这么定义的:
The server should maintain one browser per session. Commands sent to a session will be directed to the corresponding browser.
也就是说sessionId
表示了remote server和浏览器的一个会话,指令经过这个会话变成对于浏览器的一个操做。
element
。这一部分用来表示具体的指令。而selenium.webdriver.remote.command.Command
类里的常量指令又在各个具体的相似find_elements
的实例方法中做为execute
方法的参数来使用,这样就实现了selenium.webdriver.remote.webdriver.WebDriver
类中实现各类操做的实例方法与WebDriver wire protocol中定义的指令的一一对应。
而selenium.webdriver.remote.webelement.WebElement
中各类在WebElement上的操做也是用相似的原理实现的。
实例方法execute
的另外一个参数params
则是用来保存指令的参数的,这个参数将转化为JSON格式,做为HTTP请求的body发送到remote server。
remote server在执行完对浏览器的操做后获得的数据将做为HTTP Response的body返回给测试代码,测试代码通过解析处理后获得想要的数据。
这一部分属于各个浏览器开发者和Webdriver开发者的范畴,因此咱们不须要太关注,咱们所关心的主要仍是测试代码和Webdriver的关系,就好像出租车驾驶员如何驾驶汽车咱们不须要关心同样。
最后经过这个关系图来简单的描述Selenium三个组成部分的关系。经过对python selenium库的分析,但愿可以帮助你们对selenium和webdriver的实现原理有更进一步的了解,在平常的自动化脚本开发中更加快捷的定位问题和解决问题。