webdriver.py 34 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057
  1. # Licensed to the Software Freedom Conservancy (SFC) under one
  2. # or more contributor license agreements. See the NOTICE file
  3. # distributed with this work for additional information
  4. # regarding copyright ownership. The SFC licenses this file
  5. # to you under the Apache License, Version 2.0 (the
  6. # "License"); you may not use this file except in compliance
  7. # with the License. You may obtain a copy of the License at
  8. #
  9. # http://www.apache.org/licenses/LICENSE-2.0
  10. #
  11. # Unless required by applicable law or agreed to in writing,
  12. # software distributed under the License is distributed on an
  13. # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  14. # KIND, either express or implied. See the License for the
  15. # specific language governing permissions and limitations
  16. # under the License.
  17. """The WebDriver implementation."""
  18. import base64
  19. import warnings
  20. from contextlib import contextmanager
  21. from .command import Command
  22. from .webelement import WebElement
  23. from .remote_connection import RemoteConnection
  24. from .errorhandler import ErrorHandler
  25. from .switch_to import SwitchTo
  26. from .mobile import Mobile
  27. from .file_detector import FileDetector, LocalFileDetector
  28. from selenium.common.exceptions import (InvalidArgumentException,
  29. WebDriverException)
  30. from selenium.webdriver.common.by import By
  31. from selenium.webdriver.common.html5.application_cache import ApplicationCache
  32. try:
  33. str = basestring
  34. except NameError:
  35. pass
  36. class WebDriver(object):
  37. """
  38. Controls a browser by sending commands to a remote server.
  39. This server is expected to be running the WebDriver wire protocol
  40. as defined at
  41. https://github.com/SeleniumHQ/selenium/wiki/JsonWireProtocol
  42. :Attributes:
  43. - session_id - String ID of the browser session started and controlled by this WebDriver.
  44. - capabilities - Dictionaty of effective capabilities of this browser session as returned
  45. by the remote server. See https://github.com/SeleniumHQ/selenium/wiki/DesiredCapabilities
  46. - command_executor - remote_connection.RemoteConnection object used to execute commands.
  47. - error_handler - errorhandler.ErrorHandler object used to handle errors.
  48. """
  49. _web_element_cls = WebElement
  50. def __init__(self, command_executor='http://127.0.0.1:4444/wd/hub',
  51. desired_capabilities=None, browser_profile=None, proxy=None,
  52. keep_alive=False, file_detector=None):
  53. """
  54. Create a new driver that will issue commands using the wire protocol.
  55. :Args:
  56. - command_executor - Either a string representing URL of the remote server or a custom
  57. remote_connection.RemoteConnection object. Defaults to 'http://127.0.0.1:4444/wd/hub'.
  58. - desired_capabilities - A dictionary of capabilities to request when
  59. starting the browser session. Required parameter.
  60. - browser_profile - A selenium.webdriver.firefox.firefox_profile.FirefoxProfile object.
  61. Only used if Firefox is requested. Optional.
  62. - proxy - A selenium.webdriver.common.proxy.Proxy object. The browser session will
  63. be started with given proxy settings, if possible. Optional.
  64. - keep_alive - Whether to configure remote_connection.RemoteConnection to use
  65. HTTP keep-alive. Defaults to False.
  66. - file_detector - Pass custom file detector object during instantiation. If None,
  67. then default LocalFileDetector() will be used.
  68. """
  69. if desired_capabilities is None:
  70. raise WebDriverException("Desired Capabilities can't be None")
  71. if not isinstance(desired_capabilities, dict):
  72. raise WebDriverException("Desired Capabilities must be a dictionary")
  73. if proxy is not None:
  74. warnings.warn("Please use FirefoxOptions to set proxy",
  75. DeprecationWarning)
  76. proxy.add_to_capabilities(desired_capabilities)
  77. self.command_executor = command_executor
  78. if type(self.command_executor) is bytes or isinstance(self.command_executor, str):
  79. self.command_executor = RemoteConnection(command_executor, keep_alive=keep_alive)
  80. self._is_remote = True
  81. self.session_id = None
  82. self.capabilities = {}
  83. self.error_handler = ErrorHandler()
  84. self.start_client()
  85. if browser_profile is not None:
  86. warnings.warn("Please use FirefoxOptions to set browser profile",
  87. DeprecationWarning)
  88. self.start_session(desired_capabilities, browser_profile)
  89. self._switch_to = SwitchTo(self)
  90. self._mobile = Mobile(self)
  91. self.file_detector = file_detector or LocalFileDetector()
  92. def __repr__(self):
  93. return '<{0.__module__}.{0.__name__} (session="{1}")>'.format(
  94. type(self), self.session_id)
  95. @contextmanager
  96. def file_detector_context(self, file_detector_class, *args, **kwargs):
  97. """
  98. Overrides the current file detector (if necessary) in limited context.
  99. Ensures the original file detector is set afterwards.
  100. Example:
  101. with webdriver.file_detector_context(UselessFileDetector):
  102. someinput.send_keys('/etc/hosts')
  103. :Args:
  104. - file_detector_class - Class of the desired file detector. If the class is different
  105. from the current file_detector, then the class is instantiated with args and kwargs
  106. and used as a file detector during the duration of the context manager.
  107. - args - Optional arguments that get passed to the file detector class during
  108. instantiation.
  109. - kwargs - Keyword arguments, passed the same way as args.
  110. """
  111. last_detector = None
  112. if not isinstance(self.file_detector, file_detector_class):
  113. last_detector = self.file_detector
  114. self.file_detector = file_detector_class(*args, **kwargs)
  115. try:
  116. yield
  117. finally:
  118. if last_detector is not None:
  119. self.file_detector = last_detector
  120. @property
  121. def mobile(self):
  122. return self._mobile
  123. @property
  124. def name(self):
  125. """Returns the name of the underlying browser for this instance.
  126. :Usage:
  127. - driver.name
  128. """
  129. if 'browserName' in self.capabilities:
  130. return self.capabilities['browserName']
  131. else:
  132. raise KeyError('browserName not specified in session capabilities')
  133. def start_client(self):
  134. """
  135. Called before starting a new session. This method may be overridden
  136. to define custom startup behavior.
  137. """
  138. pass
  139. def stop_client(self):
  140. """
  141. Called after executing a quit command. This method may be overridden
  142. to define custom shutdown behavior.
  143. """
  144. pass
  145. def start_session(self, capabilities, browser_profile=None):
  146. """
  147. Creates a new session with the desired capabilities.
  148. :Args:
  149. - browser_name - The name of the browser to request.
  150. - version - Which browser version to request.
  151. - platform - Which platform to request the browser on.
  152. - javascript_enabled - Whether the new session should support JavaScript.
  153. - browser_profile - A selenium.webdriver.firefox.firefox_profile.FirefoxProfile object. Only used if Firefox is requested.
  154. """
  155. if not isinstance(capabilities, dict):
  156. raise InvalidArgumentException("Capabilities must be a dictionary")
  157. w3c_caps = {"firstMatch": [], "alwaysMatch": {}}
  158. if browser_profile:
  159. if "moz:firefoxOptions" in capabilities:
  160. capabilities["moz:firefoxOptions"]["profile"] = browser_profile.encoded
  161. else:
  162. capabilities.update({'firefox_profile': browser_profile.encoded})
  163. w3c_caps["alwaysMatch"].update(capabilities)
  164. parameters = {"capabilities": w3c_caps,
  165. "desiredCapabilities": capabilities}
  166. response = self.execute(Command.NEW_SESSION, parameters)
  167. if 'sessionId' not in response:
  168. response = response['value']
  169. self.session_id = response['sessionId']
  170. self.capabilities = response.get('value')
  171. # if capabilities is none we are probably speaking to
  172. # a W3C endpoint
  173. if self.capabilities is None:
  174. self.capabilities = response.get('capabilities')
  175. # Double check to see if we have a W3C Compliant browser
  176. self.w3c = response.get('status') is None
  177. def _wrap_value(self, value):
  178. if isinstance(value, dict):
  179. converted = {}
  180. for key, val in value.items():
  181. converted[key] = self._wrap_value(val)
  182. return converted
  183. elif isinstance(value, self._web_element_cls):
  184. return {'ELEMENT': value.id, 'element-6066-11e4-a52e-4f735466cecf': value.id}
  185. elif isinstance(value, list):
  186. return list(self._wrap_value(item) for item in value)
  187. else:
  188. return value
  189. def create_web_element(self, element_id):
  190. """Creates a web element with the specified `element_id`."""
  191. return self._web_element_cls(self, element_id, w3c=self.w3c)
  192. def _unwrap_value(self, value):
  193. if isinstance(value, dict):
  194. if 'ELEMENT' in value or 'element-6066-11e4-a52e-4f735466cecf' in value:
  195. wrapped_id = value.get('ELEMENT', None)
  196. if wrapped_id:
  197. return self.create_web_element(value['ELEMENT'])
  198. else:
  199. return self.create_web_element(value['element-6066-11e4-a52e-4f735466cecf'])
  200. else:
  201. for key, val in value.items():
  202. value[key] = self._unwrap_value(val)
  203. return value
  204. elif isinstance(value, list):
  205. return list(self._unwrap_value(item) for item in value)
  206. else:
  207. return value
  208. def execute(self, driver_command, params=None):
  209. """
  210. Sends a command to be executed by a command.CommandExecutor.
  211. :Args:
  212. - driver_command: The name of the command to execute as a string.
  213. - params: A dictionary of named parameters to send with the command.
  214. :Returns:
  215. The command's JSON response loaded into a dictionary object.
  216. """
  217. if self.session_id is not None:
  218. if not params:
  219. params = {'sessionId': self.session_id}
  220. elif 'sessionId' not in params:
  221. params['sessionId'] = self.session_id
  222. params = self._wrap_value(params)
  223. response = self.command_executor.execute(driver_command, params)
  224. if response:
  225. self.error_handler.check_response(response)
  226. response['value'] = self._unwrap_value(
  227. response.get('value', None))
  228. return response
  229. # If the server doesn't send a response, assume the command was
  230. # a success
  231. return {'success': 0, 'value': None, 'sessionId': self.session_id}
  232. def get(self, url):
  233. """
  234. Loads a web page in the current browser session.
  235. """
  236. self.execute(Command.GET, {'url': url})
  237. @property
  238. def title(self):
  239. """Returns the title of the current page.
  240. :Usage:
  241. driver.title
  242. """
  243. resp = self.execute(Command.GET_TITLE)
  244. return resp['value'] if resp['value'] is not None else ""
  245. def find_element_by_id(self, id_):
  246. """Finds an element by id.
  247. :Args:
  248. - id\_ - The id of the element to be found.
  249. :Usage:
  250. driver.find_element_by_id('foo')
  251. """
  252. return self.find_element(by=By.ID, value=id_)
  253. def find_elements_by_id(self, id_):
  254. """
  255. Finds multiple elements by id.
  256. :Args:
  257. - id\_ - The id of the elements to be found.
  258. :Usage:
  259. driver.find_elements_by_id('foo')
  260. """
  261. return self.find_elements(by=By.ID, value=id_)
  262. def find_element_by_xpath(self, xpath):
  263. """
  264. Finds an element by xpath.
  265. :Args:
  266. - xpath - The xpath locator of the element to find.
  267. :Usage:
  268. driver.find_element_by_xpath('//div/td[1]')
  269. """
  270. return self.find_element(by=By.XPATH, value=xpath)
  271. def find_elements_by_xpath(self, xpath):
  272. """
  273. Finds multiple elements by xpath.
  274. :Args:
  275. - xpath - The xpath locator of the elements to be found.
  276. :Usage:
  277. driver.find_elements_by_xpath("//div[contains(@class, 'foo')]")
  278. """
  279. return self.find_elements(by=By.XPATH, value=xpath)
  280. def find_element_by_link_text(self, link_text):
  281. """
  282. Finds an element by link text.
  283. :Args:
  284. - link_text: The text of the element to be found.
  285. :Usage:
  286. driver.find_element_by_link_text('Sign In')
  287. """
  288. return self.find_element(by=By.LINK_TEXT, value=link_text)
  289. def find_elements_by_link_text(self, text):
  290. """
  291. Finds elements by link text.
  292. :Args:
  293. - link_text: The text of the elements to be found.
  294. :Usage:
  295. driver.find_elements_by_link_text('Sign In')
  296. """
  297. return self.find_elements(by=By.LINK_TEXT, value=text)
  298. def find_element_by_partial_link_text(self, link_text):
  299. """
  300. Finds an element by a partial match of its link text.
  301. :Args:
  302. - link_text: The text of the element to partially match on.
  303. :Usage:
  304. driver.find_element_by_partial_link_text('Sign')
  305. """
  306. return self.find_element(by=By.PARTIAL_LINK_TEXT, value=link_text)
  307. def find_elements_by_partial_link_text(self, link_text):
  308. """
  309. Finds elements by a partial match of their link text.
  310. :Args:
  311. - link_text: The text of the element to partial match on.
  312. :Usage:
  313. driver.find_element_by_partial_link_text('Sign')
  314. """
  315. return self.find_elements(by=By.PARTIAL_LINK_TEXT, value=link_text)
  316. def find_element_by_name(self, name):
  317. """
  318. Finds an element by name.
  319. :Args:
  320. - name: The name of the element to find.
  321. :Usage:
  322. driver.find_element_by_name('foo')
  323. """
  324. return self.find_element(by=By.NAME, value=name)
  325. def find_elements_by_name(self, name):
  326. """
  327. Finds elements by name.
  328. :Args:
  329. - name: The name of the elements to find.
  330. :Usage:
  331. driver.find_elements_by_name('foo')
  332. """
  333. return self.find_elements(by=By.NAME, value=name)
  334. def find_element_by_tag_name(self, name):
  335. """
  336. Finds an element by tag name.
  337. :Args:
  338. - name: The tag name of the element to find.
  339. :Usage:
  340. driver.find_element_by_tag_name('foo')
  341. """
  342. return self.find_element(by=By.TAG_NAME, value=name)
  343. def find_elements_by_tag_name(self, name):
  344. """
  345. Finds elements by tag name.
  346. :Args:
  347. - name: The tag name the use when finding elements.
  348. :Usage:
  349. driver.find_elements_by_tag_name('foo')
  350. """
  351. return self.find_elements(by=By.TAG_NAME, value=name)
  352. def find_element_by_class_name(self, name):
  353. """
  354. Finds an element by class name.
  355. :Args:
  356. - name: The class name of the element to find.
  357. :Usage:
  358. driver.find_element_by_class_name('foo')
  359. """
  360. return self.find_element(by=By.CLASS_NAME, value=name)
  361. def find_elements_by_class_name(self, name):
  362. """
  363. Finds elements by class name.
  364. :Args:
  365. - name: The class name of the elements to find.
  366. :Usage:
  367. driver.find_elements_by_class_name('foo')
  368. """
  369. return self.find_elements(by=By.CLASS_NAME, value=name)
  370. def find_element_by_css_selector(self, css_selector):
  371. """
  372. Finds an element by css selector.
  373. :Args:
  374. - css_selector: The css selector to use when finding elements.
  375. :Usage:
  376. driver.find_element_by_css_selector('#foo')
  377. """
  378. return self.find_element(by=By.CSS_SELECTOR, value=css_selector)
  379. def find_elements_by_css_selector(self, css_selector):
  380. """
  381. Finds elements by css selector.
  382. :Args:
  383. - css_selector: The css selector to use when finding elements.
  384. :Usage:
  385. driver.find_elements_by_css_selector('.foo')
  386. """
  387. return self.find_elements(by=By.CSS_SELECTOR, value=css_selector)
  388. def execute_script(self, script, *args):
  389. """
  390. Synchronously Executes JavaScript in the current window/frame.
  391. :Args:
  392. - script: The JavaScript to execute.
  393. - \*args: Any applicable arguments for your JavaScript.
  394. :Usage:
  395. driver.execute_script('document.title')
  396. """
  397. converted_args = list(args)
  398. command = None
  399. if self.w3c:
  400. command = Command.W3C_EXECUTE_SCRIPT
  401. else:
  402. command = Command.EXECUTE_SCRIPT
  403. return self.execute(command, {
  404. 'script': script,
  405. 'args': converted_args})['value']
  406. def execute_async_script(self, script, *args):
  407. """
  408. Asynchronously Executes JavaScript in the current window/frame.
  409. :Args:
  410. - script: The JavaScript to execute.
  411. - \*args: Any applicable arguments for your JavaScript.
  412. :Usage:
  413. driver.execute_async_script('document.title')
  414. """
  415. converted_args = list(args)
  416. if self.w3c:
  417. command = Command.W3C_EXECUTE_SCRIPT_ASYNC
  418. else:
  419. command = Command.EXECUTE_ASYNC_SCRIPT
  420. return self.execute(command, {
  421. 'script': script,
  422. 'args': converted_args})['value']
  423. @property
  424. def current_url(self):
  425. """
  426. Gets the URL of the current page.
  427. :Usage:
  428. driver.current_url
  429. """
  430. return self.execute(Command.GET_CURRENT_URL)['value']
  431. @property
  432. def page_source(self):
  433. """
  434. Gets the source of the current page.
  435. :Usage:
  436. driver.page_source
  437. """
  438. return self.execute(Command.GET_PAGE_SOURCE)['value']
  439. def close(self):
  440. """
  441. Closes the current window.
  442. :Usage:
  443. driver.close()
  444. """
  445. self.execute(Command.CLOSE)
  446. def quit(self):
  447. """
  448. Quits the driver and closes every associated window.
  449. :Usage:
  450. driver.quit()
  451. """
  452. try:
  453. self.execute(Command.QUIT)
  454. finally:
  455. self.stop_client()
  456. @property
  457. def current_window_handle(self):
  458. """
  459. Returns the handle of the current window.
  460. :Usage:
  461. driver.current_window_handle
  462. """
  463. if self.w3c:
  464. return self.execute(Command.W3C_GET_CURRENT_WINDOW_HANDLE)['value']
  465. else:
  466. return self.execute(Command.GET_CURRENT_WINDOW_HANDLE)['value']
  467. @property
  468. def window_handles(self):
  469. """
  470. Returns the handles of all windows within the current session.
  471. :Usage:
  472. driver.window_handles
  473. """
  474. if self.w3c:
  475. return self.execute(Command.W3C_GET_WINDOW_HANDLES)['value']
  476. else:
  477. return self.execute(Command.GET_WINDOW_HANDLES)['value']
  478. def maximize_window(self):
  479. """
  480. Maximizes the current window that webdriver is using
  481. """
  482. command = Command.MAXIMIZE_WINDOW
  483. if self.w3c:
  484. command = Command.W3C_MAXIMIZE_WINDOW
  485. self.execute(command, {"windowHandle": "current"})
  486. @property
  487. def switch_to(self):
  488. return self._switch_to
  489. # Target Locators
  490. def switch_to_active_element(self):
  491. """ Deprecated use driver.switch_to.active_element
  492. """
  493. warnings.warn("use driver.switch_to.active_element instead", DeprecationWarning)
  494. return self._switch_to.active_element
  495. def switch_to_window(self, window_name):
  496. """ Deprecated use driver.switch_to.window
  497. """
  498. warnings.warn("use driver.switch_to.window instead", DeprecationWarning)
  499. self._switch_to.window(window_name)
  500. def switch_to_frame(self, frame_reference):
  501. """ Deprecated use driver.switch_to.frame
  502. """
  503. warnings.warn("use driver.switch_to.frame instead", DeprecationWarning)
  504. self._switch_to.frame(frame_reference)
  505. def switch_to_default_content(self):
  506. """ Deprecated use driver.switch_to.default_content
  507. """
  508. warnings.warn("use driver.switch_to.default_content instead", DeprecationWarning)
  509. self._switch_to.default_content()
  510. def switch_to_alert(self):
  511. """ Deprecated use driver.switch_to.alert
  512. """
  513. warnings.warn("use driver.switch_to.alert instead", DeprecationWarning)
  514. return self._switch_to.alert
  515. # Navigation
  516. def back(self):
  517. """
  518. Goes one step backward in the browser history.
  519. :Usage:
  520. driver.back()
  521. """
  522. self.execute(Command.GO_BACK)
  523. def forward(self):
  524. """
  525. Goes one step forward in the browser history.
  526. :Usage:
  527. driver.forward()
  528. """
  529. self.execute(Command.GO_FORWARD)
  530. def refresh(self):
  531. """
  532. Refreshes the current page.
  533. :Usage:
  534. driver.refresh()
  535. """
  536. self.execute(Command.REFRESH)
  537. # Options
  538. def get_cookies(self):
  539. """
  540. Returns a set of dictionaries, corresponding to cookies visible in the current session.
  541. :Usage:
  542. driver.get_cookies()
  543. """
  544. return self.execute(Command.GET_ALL_COOKIES)['value']
  545. def get_cookie(self, name):
  546. """
  547. Get a single cookie by name. Returns the cookie if found, None if not.
  548. :Usage:
  549. driver.get_cookie('my_cookie')
  550. """
  551. cookies = self.get_cookies()
  552. for cookie in cookies:
  553. if cookie['name'] == name:
  554. return cookie
  555. return None
  556. def delete_cookie(self, name):
  557. """
  558. Deletes a single cookie with the given name.
  559. :Usage:
  560. driver.delete_cookie('my_cookie')
  561. """
  562. self.execute(Command.DELETE_COOKIE, {'name': name})
  563. def delete_all_cookies(self):
  564. """
  565. Delete all cookies in the scope of the session.
  566. :Usage:
  567. driver.delete_all_cookies()
  568. """
  569. self.execute(Command.DELETE_ALL_COOKIES)
  570. def add_cookie(self, cookie_dict):
  571. """
  572. Adds a cookie to your current session.
  573. :Args:
  574. - cookie_dict: A dictionary object, with required keys - "name" and "value";
  575. optional keys - "path", "domain", "secure", "expiry"
  576. Usage:
  577. driver.add_cookie({'name' : 'foo', 'value' : 'bar'})
  578. driver.add_cookie({'name' : 'foo', 'value' : 'bar', 'path' : '/'})
  579. driver.add_cookie({'name' : 'foo', 'value' : 'bar', 'path' : '/', 'secure':True})
  580. """
  581. self.execute(Command.ADD_COOKIE, {'cookie': cookie_dict})
  582. # Timeouts
  583. def implicitly_wait(self, time_to_wait):
  584. """
  585. Sets a sticky timeout to implicitly wait for an element to be found,
  586. or a command to complete. This method only needs to be called one
  587. time per session. To set the timeout for calls to
  588. execute_async_script, see set_script_timeout.
  589. :Args:
  590. - time_to_wait: Amount of time to wait (in seconds)
  591. :Usage:
  592. driver.implicitly_wait(30)
  593. """
  594. if self.w3c:
  595. self.execute(Command.SET_TIMEOUTS, {
  596. 'implicit': int(float(time_to_wait) * 1000)})
  597. else:
  598. self.execute(Command.IMPLICIT_WAIT, {
  599. 'ms': float(time_to_wait) * 1000})
  600. def set_script_timeout(self, time_to_wait):
  601. """
  602. Set the amount of time that the script should wait during an
  603. execute_async_script call before throwing an error.
  604. :Args:
  605. - time_to_wait: The amount of time to wait (in seconds)
  606. :Usage:
  607. driver.set_script_timeout(30)
  608. """
  609. if self.w3c:
  610. self.execute(Command.SET_TIMEOUTS, {
  611. 'script': int(float(time_to_wait) * 1000)})
  612. else:
  613. self.execute(Command.SET_SCRIPT_TIMEOUT, {
  614. 'ms': float(time_to_wait) * 1000})
  615. def set_page_load_timeout(self, time_to_wait):
  616. """
  617. Set the amount of time to wait for a page load to complete
  618. before throwing an error.
  619. :Args:
  620. - time_to_wait: The amount of time to wait
  621. :Usage:
  622. driver.set_page_load_timeout(30)
  623. """
  624. try:
  625. self.execute(Command.SET_TIMEOUTS, {
  626. 'pageLoad': int(float(time_to_wait) * 1000)})
  627. except WebDriverException:
  628. self.execute(Command.SET_TIMEOUTS, {
  629. 'ms': float(time_to_wait) * 1000,
  630. 'type': 'page load'})
  631. def find_element(self, by=By.ID, value=None):
  632. """
  633. 'Private' method used by the find_element_by_* methods.
  634. :Usage:
  635. Use the corresponding find_element_by_* instead of this.
  636. :rtype: WebElement
  637. """
  638. if self.w3c:
  639. if by == By.ID:
  640. by = By.CSS_SELECTOR
  641. value = '[id="%s"]' % value
  642. elif by == By.TAG_NAME:
  643. by = By.CSS_SELECTOR
  644. elif by == By.CLASS_NAME:
  645. by = By.CSS_SELECTOR
  646. value = ".%s" % value
  647. elif by == By.NAME:
  648. by = By.CSS_SELECTOR
  649. value = '[name="%s"]' % value
  650. return self.execute(Command.FIND_ELEMENT, {
  651. 'using': by,
  652. 'value': value})['value']
  653. def find_elements(self, by=By.ID, value=None):
  654. """
  655. 'Private' method used by the find_elements_by_* methods.
  656. :Usage:
  657. Use the corresponding find_elements_by_* instead of this.
  658. :rtype: list of WebElement
  659. """
  660. if self.w3c:
  661. if by == By.ID:
  662. by = By.CSS_SELECTOR
  663. value = '[id="%s"]' % value
  664. elif by == By.TAG_NAME:
  665. by = By.CSS_SELECTOR
  666. elif by == By.CLASS_NAME:
  667. by = By.CSS_SELECTOR
  668. value = ".%s" % value
  669. elif by == By.NAME:
  670. by = By.CSS_SELECTOR
  671. value = '[name="%s"]' % value
  672. return self.execute(Command.FIND_ELEMENTS, {
  673. 'using': by,
  674. 'value': value})['value']
  675. @property
  676. def desired_capabilities(self):
  677. """
  678. returns the drivers current desired capabilities being used
  679. """
  680. return self.capabilities
  681. def get_screenshot_as_file(self, filename):
  682. """
  683. Gets the screenshot of the current window. Returns False if there is
  684. any IOError, else returns True. Use full paths in your filename.
  685. :Args:
  686. - filename: The full path you wish to save your screenshot to.
  687. :Usage:
  688. driver.get_screenshot_as_file('/Screenshots/foo.png')
  689. """
  690. png = self.get_screenshot_as_png()
  691. try:
  692. with open(filename, 'wb') as f:
  693. f.write(png)
  694. except IOError:
  695. return False
  696. finally:
  697. del png
  698. return True
  699. def save_screenshot(self, filename):
  700. """
  701. Gets the screenshot of the current window. Returns False if there is
  702. any IOError, else returns True. Use full paths in your filename.
  703. :Args:
  704. - filename: The full path you wish to save your screenshot to.
  705. :Usage:
  706. driver.save_screenshot('/Screenshots/foo.png')
  707. """
  708. return self.get_screenshot_as_file(filename)
  709. def get_screenshot_as_png(self):
  710. """
  711. Gets the screenshot of the current window as a binary data.
  712. :Usage:
  713. driver.get_screenshot_as_png()
  714. """
  715. return base64.b64decode(self.get_screenshot_as_base64().encode('ascii'))
  716. def get_screenshot_as_base64(self):
  717. """
  718. Gets the screenshot of the current window as a base64 encoded string
  719. which is useful in embedded images in HTML.
  720. :Usage:
  721. driver.get_screenshot_as_base64()
  722. """
  723. return self.execute(Command.SCREENSHOT)['value']
  724. def set_window_size(self, width, height, windowHandle='current'):
  725. """
  726. Sets the width and height of the current window. (window.resizeTo)
  727. :Args:
  728. - width: the width in pixels to set the window to
  729. - height: the height in pixels to set the window to
  730. :Usage:
  731. driver.set_window_size(800,600)
  732. """
  733. command = Command.SET_WINDOW_SIZE
  734. if self.w3c:
  735. command = Command.W3C_SET_WINDOW_SIZE
  736. self.execute(command, {
  737. 'width': int(width),
  738. 'height': int(height),
  739. 'windowHandle': windowHandle})
  740. def get_window_size(self, windowHandle='current'):
  741. """
  742. Gets the width and height of the current window.
  743. :Usage:
  744. driver.get_window_size()
  745. """
  746. command = Command.GET_WINDOW_SIZE
  747. if self.w3c:
  748. command = Command.W3C_GET_WINDOW_SIZE
  749. size = self.execute(command, {'windowHandle': windowHandle})
  750. if size.get('value', None) is not None:
  751. return size['value']
  752. else:
  753. return size
  754. def set_window_position(self, x, y, windowHandle='current'):
  755. """
  756. Sets the x,y position of the current window. (window.moveTo)
  757. :Args:
  758. - x: the x-coordinate in pixels to set the window position
  759. - y: the y-coordinate in pixels to set the window position
  760. :Usage:
  761. driver.set_window_position(0,0)
  762. """
  763. if self.w3c:
  764. return self.execute(Command.W3C_SET_WINDOW_POSITION, {
  765. 'x': int(x),
  766. 'y': int(y)
  767. })
  768. else:
  769. self.execute(Command.SET_WINDOW_POSITION,
  770. {
  771. 'x': int(x),
  772. 'y': int(y),
  773. 'windowHandle': windowHandle
  774. })
  775. def get_window_position(self, windowHandle='current'):
  776. """
  777. Gets the x,y position of the current window.
  778. :Usage:
  779. driver.get_window_position()
  780. """
  781. if self.w3c:
  782. return self.execute(Command.W3C_GET_WINDOW_POSITION)['value']
  783. else:
  784. return self.execute(Command.GET_WINDOW_POSITION, {
  785. 'windowHandle': windowHandle})['value']
  786. def get_window_rect(self):
  787. """
  788. Gets the x, y coordinates of the window as well as height and width of
  789. the current window.
  790. :Usage:
  791. driver.get_window_rect()
  792. """
  793. return self.execute(Command.GET_WINDOW_RECT)['value']
  794. def set_window_rect(self, x=None, y=None, width=None, height=None):
  795. """
  796. Sets the x, y coordinates of the window as well as height and width of
  797. the current window.
  798. :Usage:
  799. driver.set_window_rect(x=10, y=10)
  800. driver.set_window_rect(width=100, height=200)
  801. driver.set_window_rect(x=10, y=10, width=100, height=200)
  802. """
  803. if (x is None and y is None) and (height is None and width is None):
  804. raise InvalidArgumentException("x and y or height and width need values")
  805. return self.execute(Command.SET_WINDOW_RECT, {"x": x, "y": y,
  806. "width": width,
  807. "height": height})['value']
  808. @property
  809. def file_detector(self):
  810. return self._file_detector
  811. @file_detector.setter
  812. def file_detector(self, detector):
  813. """
  814. Set the file detector to be used when sending keyboard input.
  815. By default, this is set to a file detector that does nothing.
  816. see FileDetector
  817. see LocalFileDetector
  818. see UselessFileDetector
  819. :Args:
  820. - detector: The detector to use. Must not be None.
  821. """
  822. if detector is None:
  823. raise WebDriverException("You may not set a file detector that is null")
  824. if not isinstance(detector, FileDetector):
  825. raise WebDriverException("Detector has to be instance of FileDetector")
  826. self._file_detector = detector
  827. @property
  828. def orientation(self):
  829. """
  830. Gets the current orientation of the device
  831. :Usage:
  832. orientation = driver.orientation
  833. """
  834. return self.execute(Command.GET_SCREEN_ORIENTATION)['value']
  835. @orientation.setter
  836. def orientation(self, value):
  837. """
  838. Sets the current orientation of the device
  839. :Args:
  840. - value: orientation to set it to.
  841. :Usage:
  842. driver.orientation = 'landscape'
  843. """
  844. allowed_values = ['LANDSCAPE', 'PORTRAIT']
  845. if value.upper() in allowed_values:
  846. self.execute(Command.SET_SCREEN_ORIENTATION, {'orientation': value})
  847. else:
  848. raise WebDriverException("You can only set the orientation to 'LANDSCAPE' and 'PORTRAIT'")
  849. @property
  850. def application_cache(self):
  851. """ Returns a ApplicationCache Object to interact with the browser app cache"""
  852. return ApplicationCache(self)
  853. @property
  854. def log_types(self):
  855. """
  856. Gets a list of the available log types
  857. :Usage:
  858. driver.log_types
  859. """
  860. return self.execute(Command.GET_AVAILABLE_LOG_TYPES)['value']
  861. def get_log(self, log_type):
  862. """
  863. Gets the log for a given log type
  864. :Args:
  865. - log_type: type of log that which will be returned
  866. :Usage:
  867. driver.get_log('browser')
  868. driver.get_log('driver')
  869. driver.get_log('client')
  870. driver.get_log('server')
  871. """
  872. return self.execute(Command.GET_LOG, {'type': log_type})['value']