Selenium with Python 002 - 快速入门

时间:2021-01-23 18:05:54

一、简单实例演示

1.创建 python_org_search.py:

#!/usr/bin/env python

from selenium import webdriver
from selenium.webdriver.common.keys import Keys # 创建Chrome驱动实例
driver = webdriver.Chrome()
# 启动浏览器并且导航到指定URL
driver.get("http://www.python.org")
# 断言“Python”出现在浏览器标题
assert "Python" in driver.title
# 定位name属性为“q"的元素
elem = driver.find_element_by_name("q")
# 清空文本输入框,输入文字"pycon",然后回车
elem.clear()
elem.send_keys("pycon")
elem.send_keys(Keys.RETURN)
# 断言"No results found."不包含在当前页面源代码中
assert "No results found." not in driver.page_source
# 关闭浏览器
driver.close()

2.运行脚本

python python_org_search.py

二、使用Selenium编写测试用例

selenium package 本身并不提供测试框架,我们可以通过Python’s unittest module 来编写组织我们的测试用例,如下实例 “python.org 搜索功能的测试用例”

test_python_org_search.py:

#!/usr/bin/env python

import unittest
from selenium import webdriver
from selenium.webdriver.common.keys import Keys class PythonOrgSearch(unittest.TestCase):
""" 用例类继承unittest.TestCase """ def setUp(self):
""" 用例初始化,每个用例执行之前调用,通常用于初始化测试环境"""
self.driver = webdriver.Chrome() def test_search_in_python_org(self):
"""测试用例XXX,方法命名通常以test_开头"""
driver = self.driver
driver.get("http://www.python.org")
self.assertIn("Python", driver.title)
elem = driver.find_element_by_name("q")
elem.send_keys("pycon")
elem.send_keys(Keys.RETURN)
assert "No results found." not in driver.page_source def tearDown(self):
"""用例销毁,每个用例执行完成后调用,通常用于销毁测试环境""" self.driver.close() if __name__ == "__main__":
unittest.main() # 执行测试用例集

运行测试用例

python test_python_org_search.py

.
----------------------------------------------------------------------
Ran 1 test in 9.171s

OK

三、Selenium 分布式测试

Selenium Grid 可以在不同的主机上建立主节点(hub)和分支节点(node),可以使主节点上的测试用例在不同的分支节点上运行。对于不同的节点来说,可以搭建不同的测试环境(操作系统,浏览器),从而使一份测试用例得到不同环境下的执行结果。

Grid2不再提供单独的包,其功能已经集成到SeleniumServer中。

1、启动主节点hub:要使用远程WebDriver,必须先启动Selenium Server,启动后,如下提示,则说明主节点hub已经成功启动

D:\selenium>java -jar selenium-server-standalone-3.5..jar -role hub
::26.494 INFO - Selenium build info: version: '3.5.0', revision: '8def36e068'
::26.495 INFO - Launching Selenium Grid hub
-- ::27.269:INFO::main: Logging initialized @1003ms to org.seleniumhq.jetty9.util.log.StdErrLog
::27.288 INFO - Will listen on
-- ::27.352:INFO:osjs.Server:main: jetty-9.4..v20170502
-- ::27.385:INFO:osjs.session:main: DefaultSessionIdManager workerName=node0
-- ::27.386:INFO:osjs.session:main: No SessionScavenger set, using defaults
-- ::27.389:INFO:osjs.session:main: Scavenging every 600000ms
-- ::27.399:INFO:osjsh.ContextHandler:main: Started o.s.j.s.ServletContextHandler@64f6106c{/,null,AVAILABLE}
-- ::27.420:INFO:osjs.AbstractConnector:main: Started ServerConnector@10dba097{HTTP/1.1,[http/1.1]}{0.0.0.0:}
-- ::27.422:INFO:osjs.Server:main: Started @1156ms
::27.423 INFO - Nodes should register to http://10.1.102.68:4444/grid/register/

2.启动分支节点(node):

java -jar selenium-server-standalone-3.5..jar -role node -port 
java -jar selenium-server-standalone-3.5..jar -role node -port 

启动成功,可见如下提示

D:\selenium>java -jar selenium-server-standalone-3.5..jar -role node -port
::10.588 INFO - Selenium build info: version: '3.5.0', revision: '8def36e068'
::10.589 INFO - Launching a Selenium Grid node
-- ::11.283:INFO::main: Logging initialized @941ms to org.seleniumhq.jetty9.util.log.StdErrLog
::11.328 INFO - Driver class not found: com.opera.core.systems.OperaDriver
::11.349 INFO - Driver provider class org.openqa.selenium.safari.SafariDriver registration is skipped:
registration capabilities Capabilities [{browserName=safari, version=, platform=MAC}] does not match the current platform VISTA
::11.372 INFO - Using the passthrough mode handler
-- ::11.395:INFO:osjs.Server:main: jetty-9.4..v20170502
-- ::11.418:WARN:osjs.SecurityHandler:main: ServletContext@o.s.j.s.ServletContextHandler@6a28ffa4{/,null,STARTING} has uncovered
http methods for path: /
-- ::11.430:INFO:osjsh.ContextHandler:main: Started o.s.j.s.ServletContextHandler@6a28ffa4{/,null,AVAILABLE}
-- ::11.445:INFO:osjs.AbstractConnector:main: Started ServerConnector@7714e963{HTTP/1.1,[http/1.1]}{0.0.0.0:}
-- ::11.460:INFO:osjs.Server:main: Started @1118ms
::11.460 INFO - Selenium Grid node is up and ready to register to the hub
::11.477 INFO - Starting auto registration thread. Will try to register every ms.
::11.477 INFO - Registering the node to the hub: http://localhost:4444/grid/register
::11.620 INFO - The node is registered to the hub and ready to use

通过主节点控制器可以看到连接到hub的所有node信息 http://127.0.0.1:4444/grid/console

Selenium with Python 002 - 快速入门

3.通过Remote配置测试用例在节点上执行。

#!/usr/bin/env python
# -*- coding: utf-8 -*- from selenium.webdriver import Remote # 定义主机与浏览器
lists = {
'http://127.0.0.1:5555/wd/hub': 'chrome',
'http://127.0.0.1:5556/wd/hub': 'firefox',
} # 通过不同的浏览器执行脚本
for host, browser in lists.items():
print(host, browser)
driver = Remote(command_executor=host, desired_capabilities={
'platform': 'ANY',
'browserName': browser,
'version': '',
'javascriptEnabled': True
}) driver.get("http://www.baidu.com")
driver.find_element_by_id("kw").send_keys(browser)
driver.find_element_by_id("su").click()

Selenium with Python 002 - 快速入门

四、Selenium 调用远程Webdriver

上面启动的hub与node都是在同一台主机上,要想在其他主机上启动node,则必须满足以下要求:

  • 本地hub主机与远程node主机之间可以用ping命令连通
  • 远程主机必须按照用例执行的浏览器及驱动,并且驱动要放在环境变量path的目录下
  • 远程主机必须安装Java环境,因为需要运行Selenium Server

启动步骤:

1.启动本地hub主机(假设本机IP为:10.1.102.68)

java -jar selenium-server-standalone-3.5..jar -role hub

2.启动远程node主机(假设IP地址为:10.1.102.75)

java -jar selenium-server-standalone-3.5..jar -role node -port  -hub http://10.1.102.68:4444/grid/register

Selenium with Python 002 - 快速入门

***微信扫一扫,关注“python测试开发圈”,了解更多测试教程!***