AI教程网 - 未来以来,拥抱AI;新手入门,从AI教程网开始......

7. WebDriver API

Selenium教程 AI君 71℃

7. WebDriver API¶

Note

这不是一个官方的文档. 但是你可以在这访问官方文档:
官方文档.

这一章包含所有的 Selenium WebDriver 接口.

Recommended Import Style

The API definitions in this chapter shows the absolute location of classes.
However the recommended import style is as given below:

from selenium import webdriver

Then, you can access the classes like this:

webdriver.Firefox
webdriver.FirefoxProfile
webdriver.Chrome
webdriver.ChromeOptions
webdriver.Ie
webdriver.Opera
webdriver.PhantomJS
webdriver.Remote
webdriver.DesiredCapabilities
webdriver.ActionChains
webdriver.TouchActions
webdriver.Proxy

The special keys class (Keys) can be imported like this:

from selenium.webdriver.common.keys import Keys

The exception classes can be imported like this (Replace the TheNameOfTheExceptionClass with actual class name given below):

from selenium.common.exceptions import [TheNameOfTheExceptionClass]

Conventions used in the API

Some attributes are callable (or methods) and others are non-callable
(properties). All the callable attributes are ending with round
brackets.

Here is an example for property:

  • current_url

    URL of the current loaded page.

    Usage:

    driver.current_url
    

Here is an example for a method:

  • close()

    Closes the current window.

    Usage:

    driver.close()
    

7.1. Exceptions¶

Exceptions that may happen in all the webdriver code.

exception selenium.common.exceptions.ElementNotInteractableException(msg=None, screen=None, stacktrace=None)

Bases: selenium.common.exceptions.InvalidElementStateException

Thrown when an element is present in the DOM but interactions
with that element will hit another element do to paint order

exception selenium.common.exceptions.ElementNotSelectableException(msg=None, screen=None, stacktrace=None)

Bases: selenium.common.exceptions.InvalidElementStateException

Thrown when trying to select an unselectable element.

For example, selecting a ‘script’ element.

exception selenium.common.exceptions.ElementNotVisibleException(msg=None, screen=None, stacktrace=None)

Bases: selenium.common.exceptions.InvalidElementStateException

Thrown when an element is present on the DOM, but
it is not visible, and so is not able to be interacted with.

Most commonly encountered when trying to click or read text
of an element that is hidden from view.

exception selenium.common.exceptions.ErrorInResponseException(response, msg)

Bases: selenium.common.exceptions.WebDriverException

Thrown when an error has occurred on the server side.

This may happen when communicating with the firefox extension
or the remote driver server.

exception selenium.common.exceptions.ImeActivationFailedException(msg=None, screen=None, stacktrace=None)

Bases: selenium.common.exceptions.WebDriverException

Thrown when activating an IME engine has failed.

exception selenium.common.exceptions.ImeNotAvailableException(msg=None, screen=None, stacktrace=None)

Bases: selenium.common.exceptions.WebDriverException

Thrown when IME support is not available. This exception is thrown for every IME-related
method call if IME support is not available on the machine.

exception selenium.common.exceptions.InvalidArgumentException(msg=None, screen=None, stacktrace=None)

Bases: selenium.common.exceptions.WebDriverException

The arguments passed to a command are either invalid or malformed.

exception selenium.common.exceptions.InvalidCookieDomainException(msg=None, screen=None, stacktrace=None)

Bases: selenium.common.exceptions.WebDriverException

Thrown when attempting to add a cookie under a different domain
than the current URL.

exception selenium.common.exceptions.InvalidElementStateException(msg=None, screen=None, stacktrace=None)

Bases: selenium.common.exceptions.WebDriverException

exception selenium.common.exceptions.InvalidSelectorException(msg=None, screen=None, stacktrace=None)

Bases: selenium.common.exceptions.NoSuchElementException

Thrown when the selector which is used to find an element does not return
a WebElement. Currently this only happens when the selector is an xpath
expression and it is either syntactically invalid (i.e. it is not a
xpath expression) or the expression does not select WebElements
(e.g. “count(//input)”).

exception selenium.common.exceptions.InvalidSwitchToTargetException(msg=None, screen=None, stacktrace=None)

Bases: selenium.common.exceptions.WebDriverException

Thrown when frame or window target to be switched doesn’t exist.

exception selenium.common.exceptions.MoveTargetOutOfBoundsException(msg=None, screen=None, stacktrace=None)

Bases: selenium.common.exceptions.WebDriverException

Thrown when the target provided to the ActionsChains move()
method is invalid, i.e. out of document.

exception selenium.common.exceptions.NoAlertPresentException(msg=None, screen=None, stacktrace=None)

Bases: selenium.common.exceptions.WebDriverException

Thrown when switching to no presented alert.

This can be caused by calling an operation on the Alert() class when an alert is
not yet on the screen.

exception selenium.common.exceptions.NoSuchAttributeException(msg=None, screen=None, stacktrace=None)

Bases: selenium.common.exceptions.WebDriverException

Thrown when the attribute of element could not be found.

You may want to check if the attribute exists in the particular browser you are
testing against. Some browsers may have different property names for the same
property. (IE8’s .innerText vs. Firefox .textContent)

exception selenium.common.exceptions.NoSuchElementException(msg=None, screen=None, stacktrace=None)

Bases: selenium.common.exceptions.WebDriverException

Thrown when element could not be found.

If you encounter this exception, you may want to check the following:
  • Check your selector used in your find_by…
  • Element may not yet be on the screen at the time of the find operation,
    (webpage is still loading) see selenium.webdriver.support.wait.WebDriverWait()
    for how to write a wait wrapper to wait for an element to appear.
exception selenium.common.exceptions.NoSuchFrameException(msg=None, screen=None, stacktrace=None)

Bases: selenium.common.exceptions.InvalidSwitchToTargetException

Thrown when frame target to be switched doesn’t exist.

exception selenium.common.exceptions.NoSuchWindowException(msg=None, screen=None, stacktrace=None)

Bases: selenium.common.exceptions.InvalidSwitchToTargetException

Thrown when window target to be switched doesn’t exist.

To find the current set of active window handles, you can get a list
of the active window handles in the following way:

print driver.window_handles
exception selenium.common.exceptions.RemoteDriverServerException(msg=None, screen=None, stacktrace=None)

Bases: selenium.common.exceptions.WebDriverException

exception selenium.common.exceptions.StaleElementReferenceException(msg=None, screen=None, stacktrace=None)

Bases: selenium.common.exceptions.WebDriverException

Thrown when a reference to an element is now “stale”.

Stale means the element no longer appears on the DOM of the page.

Possible causes of StaleElementReferenceException include, but not limited to:
  • You are no longer on the same page, or the page may have refreshed since the element
    was located.
  • The element may have been removed and re-added to the screen, since it was located.
    Such as an element being relocated.
    This can happen typically with a javascript framework when values are updated and the
    node is rebuilt.
  • Element may have been inside an iframe or another context which was refreshed.
exception selenium.common.exceptions.TimeoutException(msg=None, screen=None, stacktrace=None)

Bases: selenium.common.exceptions.WebDriverException

Thrown when a command does not complete in enough time.

exception selenium.common.exceptions.UnableToSetCookieException(msg=None, screen=None, stacktrace=None)

Bases: selenium.common.exceptions.WebDriverException

Thrown when a driver fails to set a cookie.

exception selenium.common.exceptions.UnexpectedAlertPresentException(msg=None, screen=None, stacktrace=None, alert_text=None)

Bases: selenium.common.exceptions.WebDriverException

Thrown when an unexpected alert is appeared.

Usually raised when when an expected modal is blocking webdriver form executing any
more commands.

exception selenium.common.exceptions.UnexpectedTagNameException(msg=None, screen=None, stacktrace=None)

Bases: selenium.common.exceptions.WebDriverException

Thrown when a support class did not get an expected web element.

exception selenium.common.exceptions.WebDriverException(msg=None, screen=None, stacktrace=None)

Bases: exceptions.Exception

Base webdriver exception.

7.2. Action Chains¶

The ActionChains implementation,

class selenium.webdriver.common.action_chains.ActionChains(driver)

Bases: object

ActionChains are a way to automate low level interactions such as
mouse movements, mouse button actions, key press, and context menu interactions.
This is useful for doing more complex actions like hover over and drag and drop.

Generate user actions.
When you call methods for actions on the ActionChains object,
the actions are stored in a queue in the ActionChains object.
When you call perform(), the events are fired in the order they
are queued up.

ActionChains can be used in a chain pattern:

menu = driver.find_element_by_css_selector(".nav")
hidden_submenu = driver.find_element_by_css_selector(".nav #submenu1")

ActionChains(driver).move_to_element(menu).click(hidden_submenu).perform()

Or actions can be queued up one by one, then performed.:

menu = driver.find_element_by_css_selector(".nav")
hidden_submenu = driver.find_element_by_css_selector(".nav #submenu1")

actions = ActionChains(driver)
actions.move_to_element(menu)
actions.click(hidden_submenu)
actions.perform()

Either way, the actions are performed in the order they are called, one after
another.

click(on_element=None)

Clicks an element.

Args:
  • on_element: The element to click.
    If None, clicks on current mouse position.
click_and_hold(on_element=None)

Holds down the left mouse button on an element.

Args:
  • on_element: The element to mouse down.
    If None, clicks on current mouse position.
context_click(on_element=None)

Performs a context-click (right click) on an element.

Args:
  • on_element: The element to context-click.
    If None, clicks on current mouse position.
double_click(on_element=None)

Double-clicks an element.

Args:
  • on_element: The element to double-click.
    If None, clicks on current mouse position.
drag_and_drop(source, target)
Holds down the left mouse button on the source element,
then moves to the target element and releases the mouse button.
Args:
  • source: The element to mouse down.
  • target: The element to mouse up.
drag_and_drop_by_offset(source, xoffset, yoffset)
Holds down the left mouse button on the source element,
then moves to the target offset and releases the mouse button.
Args:
  • source: The element to mouse down.
  • xoffset: X offset to move to.
  • yoffset: Y offset to move to.
key_down(value, element=None)
Sends a key press only, without releasing it.
Should only be used with modifier keys (Control, Alt and Shift).
Args:
  • value: The modifier key to send. Values are defined in Keys class.
  • element: The element to send keys.
    If None, sends a key to current focused element.

Example, pressing ctrl+c:

ActionChains(driver).key_down(Keys.CONTROL).send_keys('c').key_up(Keys.CONTROL).perform()
key_up(value, element=None)

Releases a modifier key.

Args:
  • value: The modifier key to send. Values are defined in Keys class.
  • element: The element to send keys.
    If None, sends a key to current focused element.

Example, pressing ctrl+c:

ActionChains(driver).key_down(Keys.CONTROL).send_keys('c').key_up(Keys.CONTROL).perform()
move_by_offset(xoffset, yoffset)

Moving the mouse to an offset from current mouse position.

Args:
  • xoffset: X offset to move to, as a positive or negative integer.
  • yoffset: Y offset to move to, as a positive or negative integer.
move_to_element(to_element)

Moving the mouse to the middle of an element.

Args:
  • to_element: The WebElement to move to.
move_to_element_with_offset(to_element, xoffset, yoffset)
Move the mouse by an offset of the specified element.
Offsets are relative to the top-left corner of the element.
Args:
  • to_element: The WebElement to move to.
  • xoffset: X offset to move to.
  • yoffset: Y offset to move to.
pause(seconds)

Pause all inputs for the specified duration in seconds

perform()

Performs all stored actions.

release(on_element=None)

Releasing a held mouse button on an element.

Args:
  • on_element: The element to mouse up.
    If None, releases on current mouse position.
reset_actions()

Clears actions that are already stored on the remote end.

send_keys(*keys_to_send)

Sends keys to current focused element.

Args:
  • keys_to_send: The keys to send. Modifier keys constants can be found in the
    ‘Keys’ class.
send_keys_to_element(element, *keys_to_send)

Sends keys to an element.

Args:
  • element: The element to send keys.
  • keys_to_send: The keys to send. Modifier keys constants can be found in the
    ‘Keys’ class.

7.3. Alerts¶

The Alert implementation.

class selenium.webdriver.common.alert.Alert(driver)

Bases: object

Allows to work with alerts.

Use this class to interact with alert prompts. It contains methods for dismissing,
accepting, inputting, and getting text from alert prompts.

Accepting / Dismissing alert prompts:

Alert(driver).accept()
Alert(driver).dismiss()

Inputting a value into an alert prompt:

name_prompt = Alert(driver)
name_prompt.send_keys(“Willian Shakesphere”)
name_prompt.accept()

Reading a the text of a prompt for verification:

alert_text = Alert(driver).text
self.assertEqual(“Do you wish to quit?”, alert_text)
accept()

Accepts the alert available.

Usage::
Alert(driver).accept() # Confirm a alert dialog.

authenticate(username, password)

Send the username / password to an Authenticated dialog (like with Basic HTTP Auth).
Implicitly ‘clicks ok’

Usage::
driver.switch_to.alert.authenticate(‘cheese’, ‘secretGouda’)

Args: -username: string to be set in the username section of the dialog
-password: string to be set in the password section of the dialog
dismiss()

Dismisses the alert available.

send_keys(keysToSend)

Send Keys to the Alert.

Args:
  • keysToSend: The text to be sent to Alert.
text

Gets the text of the Alert.

7.4. Special Keys¶

The Keys implementation.

class selenium.webdriver.common.keys.Keys

Bases: object

Set of special keys codes.

ADD = u’\ue025′
ALT = u’\ue00a’
ARROW_DOWN = u’\ue015′
ARROW_LEFT = u’\ue012′
ARROW_RIGHT = u’\ue014′
ARROW_UP = u’\ue013′
BACKSPACE = u’\ue003′
BACK_SPACE = u’\ue003′
CANCEL = u’\ue001′
CLEAR = u’\ue005′
COMMAND = u’\ue03d’
CONTROL = u’\ue009′
DECIMAL = u’\ue028′
DELETE = u’\ue017′
DIVIDE = u’\ue029′
DOWN = u’\ue015′
END = u’\ue010′
ENTER = u’\ue007′
EQUALS = u’\ue019′
ESCAPE = u’\ue00c’
F1 = u’\ue031′
F10 = u’\ue03a’
F11 = u’\ue03b’
F12 = u’\ue03c’
F2 = u’\ue032′
F3 = u’\ue033′
F4 = u’\ue034′
F5 = u’\ue035′
F6 = u’\ue036′
F7 = u’\ue037′
F8 = u’\ue038′
F9 = u’\ue039′
HELP = u’\ue002′
HOME = u’\ue011′
INSERT = u’\ue016′
LEFT = u’\ue012′
LEFT_ALT = u’\ue00a’
LEFT_CONTROL = u’\ue009′
LEFT_SHIFT = u’\ue008′
META = u’\ue03d’
MULTIPLY = u’\ue024′
NULL = u’\ue000′
NUMPAD0 = u’\ue01a’
NUMPAD1 = u’\ue01b’
NUMPAD2 = u’\ue01c’
NUMPAD3 = u’\ue01d’
NUMPAD4 = u’\ue01e’
NUMPAD5 = u’\ue01f’
NUMPAD6 = u’\ue020′www.ainoob.cn » 7. WebDriver API

喜欢 (0)or分享 (0)