最後更新: 2017-12-12
介紹
Tools
- Selenium IDE
- Katalon Recorder
Download
selenium server(.jar) / firefox ide(.xpi) :
http://docs.seleniumhq.org/download/
Python bindings for Selenium(pip):
https://pypi.python.org/pypi/selenium
Install
pip install selenium
# Windows User
* pip is already installed if you are using Python 2 >=2.7.9 or Python 3 >=3.4
RC 與 WebDriver 的運作
Local (geckodriver)
More info: https://datahunter.org/geckodriver
Selenium-RC (officially deprecated)
It ‘injected' javascript functions into the browser when the browser was loaded and
then used its javascript to drive the AUT within the browser.
WebDriver
Selenium Server (java) [use Selenium Webdriver Remote]
It drives the browser directly using the browser’s built in support for automatio
Grid2
scale by distributing tests on several machines. manage multiple environments from a central point.
Selenium-IDE
Run Selenese Directly Within the Server Using -htmlSuite
java -jar selenium-server-standalone-<version-number>.jar -htmlSuite "*firefox" "http://www.google.com" "c:\absolute\path\to\my\HTMLSuite.html" "c:\absolute\path\to\my\results.html"
Webdriver(grid)
Selenium-Grid 2.0 jar file
single .jar file to get the remote Selenium-RC-Server and Selenium-Grid all in one package.
Hub
hub option:
-nodeTimeout:XXXX
the timeout in seconds before the hub automatically ends a test
(The browser will be released for another test to use.)
Hub Console:
http://hubofmachine:4444/grid/console [-log selenium.log] [-browserSideLog]
start hub
java -jar selenium-server-standalone-2.14.0.jar -role hub
Node
node option:
-registerCycle = how often in ms the node will try to register itself again.
(Allow to restart the hub without having to restart the nodes.)
start node
java -jar selenium-server-standalone-2.14.0.jar -role node \
-hub http://localhost:4444/grid/register \
-browser browserName=firefox,maxInstances=5
config file:
-role hub -hubConfig hubconfig.json # 用圖不大
-role node -nodeConfig nodeconfig.json
File: nodeconfig.json
{ "capabilities": [ { "browserName": "*firefox", "maxInstances": 5, "seleniumProtocol": "Selenium" }, { "browserName": "*googlechrome", "maxInstances": 5, "seleniumProtocol": "Selenium" }, { "browserName": "*iexplore", "maxInstances": 1, "seleniumProtocol": "Selenium" }, { "browserName": "firefox", "maxInstances": 5, "seleniumProtocol": "WebDriver" }, { "browserName": "chrome", "maxInstances": 5, "seleniumProtocol": "WebDriver" }, { "browserName": "internet explorer", "maxInstances": 1, "seleniumProtocol": "WebDriver" } ], "configuration": { "proxy": "org.openqa.grid.selenium.proxy.DefaultRemoteProxy", "maxSession": 5, "port": 5555, "host": ip, "register": true, "registerCycle": 5000, "hubPort": 4444, "hubHost": ip } }
File: hubconfig.json:
{ "host": null, "port": 4444, "newSessionWaitTimeout": -1, "servlets" : [], "prioritizer": null, "capabilityMatcher": "org.openqa.grid.internal.utils.DefaultCapabilityMatcher", "throwOnCapabilityNotPresent": true, "nodePolling": 5000, "cleanUpCycle": 5000, "timeout": 300000, "browserTimeout": 0, "maxSession": 5 }
測試
當連接成功後, 開 Browser 會見到 console 會見到:
Client
安裝方法:
pip install -U selenium
OR
dl selenium-2.41.tar.gz
tar -zxf selenium-2.41.tar.gz
cd selenium
python setup.py install
Usage Example
[1] 開 browser, 最大化 window, 打開 link, 關
from selenium import webdriver import time url = 'http://www.google.com.hk' driver = webdriver.Firefox() driver.maximize_window() # WebDriver will wait until the page has fully loaded (that is, the “onload” event has fired) # before returning control to your test or script. driver.get(url) # 用 "print driver.title" 看 title # To ensure that some results are found, make an assertion: # assert "No results found." not in driver.page_source assert "Google" in driver.title time.sleep(3) # The quit will exit entire browser whereas close will close one tab, # but if just one tab was open, by default most browser will exit entirely.: # driver.close() driver.quit()
assert
Traceback (most recent call last): File "./reuse.py", line 51, in <module> assert "Google2" in driver.title AssertionError
captureScreenshot
selenium.captureScreenshot("/tmp/" + testMethodName + ".png");
P.S.
圖片是放在 node 上的
Webdriver
alert popup
driver.switchTo().alert().accept();
upload window
$('input[type=file]', $('#upload-dialog')).first().bind("click",function(){return false;});
$('input[type=file]').first().bind("click",function(){return false;});
$('input[type=file]').bind("click",function(){return false;});
Firefox Profile
GUI
# -P, -profilemanager
firefox.exe -P
CLI
firefox.exe -firefoxProfileTemplate "c:\fprofile"
ie.
1. 用 profilemanager 建立 profile 並設定存放在 "c:\fprofile"
2. 用某 profile 行 firefox "firefox.exe -firefoxProfileTemplate c:\fprofile"
3. Checking URL: about:profiles
headless mode
# 如果不接 "-marionette" 那就再不能控制它
-headless -marionette
Full Stack
# Firefox
"C:\Program Files\Mozilla Firefox\firefox.exe" -marionette -firefoxProfileTemplate c:\fprofile
# geckodriver
geckodriver --host 192.168.88.122 --connect-existing --marionette-port 2828
#
Remote
from selenium import webdriver from selenium.webdriver.common.desired_capabilities import DesiredCapabilities executor_url = 'http://192.168.88.122:4444' #capabilities={'javascriptEnabled': 'True'} #driver = webdriver.Remote(executor_url, desired_capabilities=capabilities) driver = webdriver.Remote( command_executor=executor_url, desired_capabilities=DesiredCapabilities.FIREFOX) # Session info print driver.command_executor._url print driver.session_id
Re-using existing browser session in selenium
log
selenium.common.exceptions.SessionNotCreatedException: Message: Session is already started
override the execute function while creating the driver
def create_driver_session(session_id, executor_url): from selenium.webdriver.remote.webdriver import WebDriver as RemoteWebDriver # Save the original function, so we can revert our patch org_command_execute = RemoteWebDriver.execute def new_command_execute(self, command, params=None): if command == "newSession": # Mock the response return {'success': 0, 'value': None, 'sessionId': session_id} else: return org_command_execute(self, command, params) # Patch the function before creating the driver object RemoteWebDriver.execute = new_command_execute new_driver = webdriver.Remote(command_executor=executor_url, desired_capabilities={}) new_driver.session_id = session_id # Replace the patched function with original function RemoteWebDriver.execute = org_command_execute return new_driver driver2 = create_driver_session(session_id, executor_url)
By & find_element_by_X
By
from selenium import webdriver from selenium.webdriver.common.by import By driver = webdriver.Firefox() driver.get('http://www.google.com') q = driver.find_element(By.NAME, 'q') q.clear() q.send_keys('webdriver') q.submit()
find_element_by_X
# cleanup input driver.find_element_by_name('Locator value').clear(); driver.find_element_by_id('Locator value').clear();
Keys
# The Keys class provide keys in the keyboard like RETURN, F1, ALT etc.
from selenium.webdriver.common.keys import Keys
q = driver.find_element_by_name("q")
q.clear()
q.send_keys("webdriver")
q.send_keys(Keys.RETURN)
DOC
http://www.seleniumhq.org/docs/
http://docs.seleniumhq.org/docs/03_webdriver.jsp
http://docs.seleniumhq.org/docs/07_selenium_grid.jsp
http://docs.seleniumhq.org/docs/02_selenium_ide.jsp