Ações API Uma interface de baixo nível para fornecer ações de entrada de dispositivo virtualizadas para o navegador da web..
Além das interações de alto nível , a API de Ações oferece controle detalhado sobre o que dispositivos de entrada designados podem fazer. O Selenium fornece uma interface para 3 tipos de fontes de entrada: entrada de teclado para dispositivos de teclado, entrada de ponteiro para mouse, caneta ou dispositivos de toque, e entrada de roda para dispositivos de roda de rolagem (introduzida no Selenium 4.2). O Selenium permite que você construa comandos de ação individuais atribuídos a entradas específicas, encadeie-os e chame o método de execução associado para executá-los todos de uma vez.
Construtor de Ações Na transição do antigo Protocolo JSON Wire para o novo Protocolo W3C WebDriver, os componentes de construção de ações de baixo nível se tornaram especialmente detalhados. Isso é extremamente poderoso, mas cada dispositivo de entrada possui várias maneiras de ser utilizado e, se você precisa gerenciar mais de um dispositivo, é responsável por garantir a sincronização adequada entre eles.
Felizmente, provavelmente você não precisa aprender a usar os comandos de baixo nível diretamente, uma vez que quase tudo o que você pode querer fazer foi fornecido com um método de conveniência que combina os comandos de nível inferior para você. Todos esses métodos estão documentados nas páginas de teclado , mouse , caneta e roda .
Pausa Movimentos de ponteiro e rolagem da roda permitem que o usuário defina uma duração para a ação, mas às vezes você só precisa esperar um momento entre as ações para que as coisas funcionem corretamente.
Java
Python
CSharp
Ruby
JavaScript
Kotlin WebElement clickable = driver . findElement ( By . id ( "clickable" ));
new Actions ( driver )
. moveToElement ( clickable )
. pause ( Duration . ofSeconds ( 1 ))
. clickAndHold ()
. pause ( Duration . ofSeconds ( 1 ))
. sendKeys ( "abc" )
. perform ();
examples/java/src/test/java/dev/selenium/actions_api/ActionsTest.java
Copy
Close
package dev.selenium.actions_api ;
import dev.selenium.BaseChromeTest ;
import org.junit.jupiter.api.Assertions ;
import org.junit.jupiter.api.Test ;
import org.openqa.selenium.By ;
import org.openqa.selenium.Keys ;
import org.openqa.selenium.WebElement ;
import org.openqa.selenium.interactions.Actions ;
import org.openqa.selenium.remote.RemoteWebDriver ;
import java.time.Duration ;
public class ActionsTest extends BaseChromeTest {
@Test
public void pause () {
driver . get ( "https://www.selenium.dev/selenium/web/mouse_interaction.html" );
long start = System . currentTimeMillis ();
WebElement clickable = driver . findElement ( By . id ( "clickable" ));
new Actions ( driver )
. moveToElement ( clickable )
. pause ( Duration . ofSeconds ( 1 ))
. clickAndHold ()
. pause ( Duration . ofSeconds ( 1 ))
. sendKeys ( "abc" )
. perform ();
long duration = System . currentTimeMillis () - start ;
Assertions . assertTrue ( duration > 2000 );
Assertions . assertTrue ( duration < 3000 );
}
@Test
public void releasesAll () {
driver . get ( "https://www.selenium.dev/selenium/web/mouse_interaction.html" );
WebElement clickable = driver . findElement ( By . id ( "clickable" ));
Actions actions = new Actions ( driver );
actions . clickAndHold ( clickable )
. keyDown ( Keys . SHIFT )
. sendKeys ( "a" )
. perform ();
(( RemoteWebDriver ) driver ). resetInputState ();
actions . sendKeys ( "a" ). perform ();
Assertions . assertEquals ( "A" , String . valueOf ( clickable . getAttribute ( "value" ). charAt ( 0 )));
Assertions . assertEquals ( "a" , String . valueOf ( clickable . getAttribute ( "value" ). charAt ( 1 )));
}
}
clickable = driver . find_element ( By . ID , "clickable" )
ActionChains ( driver ) \
. move_to_element ( clickable ) \
. pause ( 1 ) \
. click_and_hold () \
. pause ( 1 ) \
. send_keys ( "abc" ) \
. perform ()
examples/python/tests/actions_api/test_actions.py
Copy
Close
from time import time
from selenium.webdriver import Keys , ActionChains
from selenium.webdriver.common.actions.action_builder import ActionBuilder
from selenium.webdriver.common.by import By
def test_pauses ( driver ):
driver . get ( 'https://selenium.dev/selenium/web/mouse_interaction.html' )
start = time ()
clickable = driver . find_element ( By . ID , "clickable" )
ActionChains ( driver ) \
. move_to_element ( clickable ) \
. pause ( 1 ) \
. click_and_hold () \
. pause ( 1 ) \
. send_keys ( "abc" ) \
. perform ()
duration = time () - start
assert duration > 2
assert duration < 3
def test_releases_all ( driver ):
driver . get ( 'https://selenium.dev/selenium/web/mouse_interaction.html' )
clickable = driver . find_element ( By . ID , "clickable" )
ActionChains ( driver ) \
. click_and_hold ( clickable ) \
. key_down ( Keys . SHIFT ) \
. key_down ( "a" ) \
. perform ()
ActionBuilder ( driver ) . clear_actions ()
ActionChains ( driver ) . key_down ( 'a' ) . perform ()
assert clickable . get_attribute ( 'value' )[ 0 ] == "A"
assert clickable . get_attribute ( 'value' )[ 1 ] == "a"
Selenium v4.2
IWebElement clickable = driver . FindElement ( By . Id ( "clickable" ));
new Actions ( driver )
. MoveToElement ( clickable )
. Pause ( TimeSpan . FromSeconds ( 1 ))
. ClickAndHold ()
. Pause ( TimeSpan . FromSeconds ( 1 ))
. SendKeys ( "abc" )
. Perform ();
examples/dotnet/SeleniumDocs/ActionsAPI/ActionsTest.cs
Copy
Close
using System ;
using Microsoft.VisualStudio.TestTools.UnitTesting ;
using OpenQA.Selenium ;
using OpenQA.Selenium.Interactions ;
namespace SeleniumDocs.ActionsAPI
{
[TestClass]
public class ActionsTest : BaseChromeTest
{
[TestMethod]
public void Pause ()
{
driver . Url = "https://selenium.dev/selenium/web/mouse_interaction.html" ;
DateTime start = DateTime . Now ;
IWebElement clickable = driver . FindElement ( By . Id ( "clickable" ));
new Actions ( driver )
. MoveToElement ( clickable )
. Pause ( TimeSpan . FromSeconds ( 1 ))
. ClickAndHold ()
. Pause ( TimeSpan . FromSeconds ( 1 ))
. SendKeys ( "abc" )
. Perform ();
TimeSpan duration = DateTime . Now - start ;
Assert . IsTrue ( duration > TimeSpan . FromSeconds ( 2 ));
Assert . IsTrue ( duration < TimeSpan . FromSeconds ( 3 ));
}
[TestMethod]
public void ReleaseAll ()
{
driver . Url = "https://selenium.dev/selenium/web/mouse_interaction.html" ;
IWebElement clickable = driver . FindElement ( By . Id ( "clickable" ));
var actions = new Actions ( driver );
actions . ClickAndHold ( clickable )
. KeyDown ( Keys . Shift )
. SendKeys ( "a" )
. Perform ();
(( WebDriver ) driver ). ResetInputState ();
actions . SendKeys ( "a" ). Perform ();
var value = clickable . GetAttribute ( "value" );
Assert . AreEqual ( "A" , value [.. 1 ]);
Assert . AreEqual ( "a" , value . Substring ( 1 , 1 ));
}
}
}
Selenium v4.2
clickable = driver . find_element ( id : 'clickable' )
driver . action
. move_to ( clickable )
. pause ( duration : 1 )
. click_and_hold
. pause ( duration : 1 )
. send_keys ( 'abc' )
. perform
examples/ruby/spec/actions_api/actions_spec.rb
Copy
Close
# frozen_string_literal: true
require 'spec_helper'
RSpec . describe 'Actions' do
let ( :driver ) { start_session }
it 'pauses' do
driver . get 'https://www.selenium.dev/selenium/web/mouse_interaction.html'
start = Time . now
clickable = driver . find_element ( id : 'clickable' )
driver . action
. move_to ( clickable )
. pause ( duration : 1 )
. click_and_hold
. pause ( duration : 1 )
. send_keys ( 'abc' )
. perform
duration = Time . now - start
expect ( duration ) . to be > 2
expect ( duration ) . to be < 3
end
it 'releases all' do
driver . get 'https://www.selenium.dev/selenium/web/mouse_interaction.html'
clickable = driver . find_element ( id : 'clickable' )
action = driver . action
. click_and_hold ( clickable )
. key_down ( :shift )
. key_down ( 'a' )
action . perform
driver . action . release_actions
action . key_down ( 'a' ) . perform
expect ( clickable . attribute ( 'value' ) [ 0 ] ) . to eq 'A'
expect ( clickable . attribute ( 'value' ) [- 1 ] ) . to eq 'a'
end
end
const start = Date . now ()
const clickable = await driver . findElement ( By . id ( 'clickable' ))
await driver . actions ()
. move ({ origin : clickable })
. pause ( 1000 )
. press ()
. pause ( 1000 )
examples/javascript/test/actionsApi/actionsTest.spec.js
Copy
Close
const { By , Key , Browser } = require ( 'selenium-webdriver' )
const { suite } = require ( 'selenium-webdriver/testing' )
const assert = require ( 'assert' )
suite ( function ( env ) {
describe ( 'Actions API - Pause and Release All Actions' , function () {
let driver
before ( async function () {
driver = await env . builder (). build ()
})
after (() => driver . quit ())
it ( 'Pause' , async function () {
await driver . get ( 'https://selenium.dev/selenium/web/mouse_interaction.html' )
const start = Date . now ()
const clickable = await driver . findElement ( By . id ( 'clickable' ))
await driver . actions ()
. move ({ origin : clickable })
. pause ( 1000 )
. press ()
. pause ( 1000 )
. sendKeys ( 'abc' )
. perform ()
const end = Date . now () - start
assert . ok ( end > 2000 )
assert . ok ( end < 4000 )
})
it ( 'Clear' , async function () {
await driver . get ( 'https://selenium.dev/selenium/web/mouse_interaction.html' )
const clickable = driver . findElement ( By . id ( 'clickable' ))
await driver . actions ()
. click ( clickable )
. keyDown ( Key . SHIFT )
. sendKeys ( 'a' )
. perform ()
await driver . actions (). clear ()
await driver . actions (). sendKeys ( 'a' ). perform ()
const value = await clickable . getAttribute ( 'value' )
assert . deepStrictEqual ( 'A' , value . substring ( 0 , 1 ))
assert . deepStrictEqual ( 'a' , value . substring ( 1 , 2 ))
})
})
}, { browsers : [ Browser . CHROME ]})
val clickable = driver . findElement ( By . id ( "clickable" ))
Actions ( driver )
. moveToElement ( clickable )
. pause ( Duration . ofSeconds ( 1 ))
. clickAndHold ()
. pause ( Duration . ofSeconds ( 1 ))
. sendKeys ( "abc" )
. perform ()
examples/kotlin/src/test/kotlin/dev/selenium/actions_api/ActionsTest.kt
Copy
Close
package dev.selenium.actions_api
import dev.selenium.BaseTest
import org.junit.jupiter.api.Assertions
import org.junit.jupiter.api.Test
import org.openqa.selenium.By
import org.openqa.selenium.Keys
import org.openqa.selenium.WebElement
import org.openqa.selenium.interactions.Actions
import org.openqa.selenium.remote.RemoteWebDriver
import java.time.Duration
class ActionsTest : BaseTest () {
@Test
fun pause () {
driver . get ( "https://www.selenium.dev/selenium/web/mouse_interaction.html" )
val start = System . currentTimeMillis ()
val clickable = driver . findElement ( By . id ( "clickable" ))
Actions ( driver )
. moveToElement ( clickable )
. pause ( Duration . ofSeconds ( 1 ))
. clickAndHold ()
. pause ( Duration . ofSeconds ( 1 ))
. sendKeys ( "abc" )
. perform ()
val duration = System . currentTimeMillis () - start
Assertions . assertTrue ( duration > 2000 )
Assertions . assertTrue ( duration < 4000 )
}
@Test
fun releasesAll () {
driver . get ( "https://www.selenium.dev/selenium/web/mouse_interaction.html" )
val clickable = driver . findElement ( By . id ( "clickable" ))
val actions = Actions ( driver )
actions . clickAndHold ( clickable )
. keyDown ( Keys . SHIFT )
. sendKeys ( "a" )
. perform ()
( driver as RemoteWebDriver ). resetInputState ()
actions . sendKeys ( "a" ). perform ()
Assertions . assertEquals ( "A" , clickable . getAttribute ( "value" ). get ( 0 ). toString ())
Assertions . assertEquals ( "a" , clickable . getAttribute ( "value" ). get ( 1 ). toString ())
}
}
Liberar Todas as Ações Um ponto importante a ser observado é que o driver lembra o estado de todos os itens de entrada ao longo de uma sessão. Mesmo se você criar uma nova instância de uma classe de ações, as teclas pressionadas e a posição do ponteiro permanecerão no estado em que uma ação previamente executada os deixou.
Existe um método especial para liberar todas as teclas pressionadas e botões do ponteiro atualmente pressionados. Esse método é implementado de maneira diferente em cada uma das linguagens porque não é executado com o método de execução (perform).
Java
Python
CSharp
Ruby
JavaScript
Kotlin (( RemoteWebDriver ) driver ). resetInputState ();
examples/java/src/test/java/dev/selenium/actions_api/ActionsTest.java
Copy
Close
package dev.selenium.actions_api ;
import dev.selenium.BaseChromeTest ;
import org.junit.jupiter.api.Assertions ;
import org.junit.jupiter.api.Test ;
import org.openqa.selenium.By ;
import org.openqa.selenium.Keys ;
import org.openqa.selenium.WebElement ;
import org.openqa.selenium.interactions.Actions ;
import org.openqa.selenium.remote.RemoteWebDriver ;
import java.time.Duration ;
public class ActionsTest extends BaseChromeTest {
@Test
public void pause () {
driver . get ( "https://www.selenium.dev/selenium/web/mouse_interaction.html" );
long start = System . currentTimeMillis ();
WebElement clickable = driver . findElement ( By . id ( "clickable" ));
new Actions ( driver )
. moveToElement ( clickable )
. pause ( Duration . ofSeconds ( 1 ))
. clickAndHold ()
. pause ( Duration . ofSeconds ( 1 ))
. sendKeys ( "abc" )
. perform ();
long duration = System . currentTimeMillis () - start ;
Assertions . assertTrue ( duration > 2000 );
Assertions . assertTrue ( duration < 3000 );
}
@Test
public void releasesAll () {
driver . get ( "https://www.selenium.dev/selenium/web/mouse_interaction.html" );
WebElement clickable = driver . findElement ( By . id ( "clickable" ));
Actions actions = new Actions ( driver );
actions . clickAndHold ( clickable )
. keyDown ( Keys . SHIFT )
. sendKeys ( "a" )
. perform ();
(( RemoteWebDriver ) driver ). resetInputState ();
actions . sendKeys ( "a" ). perform ();
Assertions . assertEquals ( "A" , String . valueOf ( clickable . getAttribute ( "value" ). charAt ( 0 )));
Assertions . assertEquals ( "a" , String . valueOf ( clickable . getAttribute ( "value" ). charAt ( 1 )));
}
}
ActionBuilder ( driver ) . clear_actions ()
examples/python/tests/actions_api/test_actions.py
Copy
Close
from time import time
from selenium.webdriver import Keys , ActionChains
from selenium.webdriver.common.actions.action_builder import ActionBuilder
from selenium.webdriver.common.by import By
def test_pauses ( driver ):
driver . get ( 'https://selenium.dev/selenium/web/mouse_interaction.html' )
start = time ()
clickable = driver . find_element ( By . ID , "clickable" )
ActionChains ( driver ) \
. move_to_element ( clickable ) \
. pause ( 1 ) \
. click_and_hold () \
. pause ( 1 ) \
. send_keys ( "abc" ) \
. perform ()
duration = time () - start
assert duration > 2
assert duration < 3
def test_releases_all ( driver ):
driver . get ( 'https://selenium.dev/selenium/web/mouse_interaction.html' )
clickable = driver . find_element ( By . ID , "clickable" )
ActionChains ( driver ) \
. click_and_hold ( clickable ) \
. key_down ( Keys . SHIFT ) \
. key_down ( "a" ) \
. perform ()
ActionBuilder ( driver ) . clear_actions ()
ActionChains ( driver ) . key_down ( 'a' ) . perform ()
assert clickable . get_attribute ( 'value' )[ 0 ] == "A"
assert clickable . get_attribute ( 'value' )[ 1 ] == "a"
(( WebDriver ) driver ). ResetInputState ();
examples/dotnet/SeleniumDocs/ActionsAPI/ActionsTest.cs
Copy
Close
using System ;
using Microsoft.VisualStudio.TestTools.UnitTesting ;
using OpenQA.Selenium ;
using OpenQA.Selenium.Interactions ;
namespace SeleniumDocs.ActionsAPI
{
[TestClass]
public class ActionsTest : BaseChromeTest
{
[TestMethod]
public void Pause ()
{
driver . Url = "https://selenium.dev/selenium/web/mouse_interaction.html" ;
DateTime start = DateTime . Now ;
IWebElement clickable = driver . FindElement ( By . Id ( "clickable" ));
new Actions ( driver )
. MoveToElement ( clickable )
. Pause ( TimeSpan . FromSeconds ( 1 ))
. ClickAndHold ()
. Pause ( TimeSpan . FromSeconds ( 1 ))
. SendKeys ( "abc" )
. Perform ();
TimeSpan duration = DateTime . Now - start ;
Assert . IsTrue ( duration > TimeSpan . FromSeconds ( 2 ));
Assert . IsTrue ( duration < TimeSpan . FromSeconds ( 3 ));
}
[TestMethod]
public void ReleaseAll ()
{
driver . Url = "https://selenium.dev/selenium/web/mouse_interaction.html" ;
IWebElement clickable = driver . FindElement ( By . Id ( "clickable" ));
var actions = new Actions ( driver );
actions . ClickAndHold ( clickable )
. KeyDown ( Keys . Shift )
. SendKeys ( "a" )
. Perform ();
(( WebDriver ) driver ). ResetInputState ();
actions . SendKeys ( "a" ). Perform ();
var value = clickable . GetAttribute ( "value" );
Assert . AreEqual ( "A" , value [.. 1 ]);
Assert . AreEqual ( "a" , value . Substring ( 1 , 1 ));
}
}
}
driver . action . release_actions
examples/ruby/spec/actions_api/actions_spec.rb
Copy
Close
# frozen_string_literal: true
require 'spec_helper'
RSpec . describe 'Actions' do
let ( :driver ) { start_session }
it 'pauses' do
driver . get 'https://www.selenium.dev/selenium/web/mouse_interaction.html'
start = Time . now
clickable = driver . find_element ( id : 'clickable' )
driver . action
. move_to ( clickable )
. pause ( duration : 1 )
. click_and_hold
. pause ( duration : 1 )
. send_keys ( 'abc' )
. perform
duration = Time . now - start
expect ( duration ) . to be > 2
expect ( duration ) . to be < 3
end
it 'releases all' do
driver . get 'https://www.selenium.dev/selenium/web/mouse_interaction.html'
clickable = driver . find_element ( id : 'clickable' )
action = driver . action
. click_and_hold ( clickable )
. key_down ( :shift )
. key_down ( 'a' )
action . perform
driver . action . release_actions
action . key_down ( 'a' ) . perform
expect ( clickable . attribute ( 'value' ) [ 0 ] ) . to eq 'A'
expect ( clickable . attribute ( 'value' ) [- 1 ] ) . to eq 'a'
end
end
examples/javascript/test/actionsApi/actionsTest.spec.js
Copy
Close
const { By , Key , Browser } = require ( 'selenium-webdriver' )
const { suite } = require ( 'selenium-webdriver/testing' )
const assert = require ( 'assert' )
suite ( function ( env ) {
describe ( 'Actions API - Pause and Release All Actions' , function () {
let driver
before ( async function () {
driver = await env . builder (). build ()
})
after (() => driver . quit ())
it ( 'Pause' , async function () {
await driver . get ( 'https://selenium.dev/selenium/web/mouse_interaction.html' )
const start = Date . now ()
const clickable = await driver . findElement ( By . id ( 'clickable' ))
await driver . actions ()
. move ({ origin : clickable })
. pause ( 1000 )
. press ()
. pause ( 1000 )
. sendKeys ( 'abc' )
. perform ()
const end = Date . now () - start
assert . ok ( end > 2000 )
assert . ok ( end < 4000 )
})
it ( 'Clear' , async function () {
await driver . get ( 'https://selenium.dev/selenium/web/mouse_interaction.html' )
const clickable = driver . findElement ( By . id ( 'clickable' ))
await driver . actions ()
. click ( clickable )
. keyDown ( Key . SHIFT )
. sendKeys ( 'a' )
. perform ()
await driver . actions (). clear ()
await driver . actions (). sendKeys ( 'a' ). perform ()
const value = await clickable . getAttribute ( 'value' )
assert . deepStrictEqual ( 'A' , value . substring ( 0 , 1 ))
assert . deepStrictEqual ( 'a' , value . substring ( 1 , 2 ))
})
})
}, { browsers : [ Browser . CHROME ]})
( driver as RemoteWebDriver ). resetInputState ()
examples/kotlin/src/test/kotlin/dev/selenium/actions_api/ActionsTest.kt
Copy
Close
package dev.selenium.actions_api
import dev.selenium.BaseTest
import org.junit.jupiter.api.Assertions
import org.junit.jupiter.api.Test
import org.openqa.selenium.By
import org.openqa.selenium.Keys
import org.openqa.selenium.WebElement
import org.openqa.selenium.interactions.Actions
import org.openqa.selenium.remote.RemoteWebDriver
import java.time.Duration
class ActionsTest : BaseTest () {
@Test
fun pause () {
driver . get ( "https://www.selenium.dev/selenium/web/mouse_interaction.html" )
val start = System . currentTimeMillis ()
val clickable = driver . findElement ( By . id ( "clickable" ))
Actions ( driver )
. moveToElement ( clickable )
. pause ( Duration . ofSeconds ( 1 ))
. clickAndHold ()
. pause ( Duration . ofSeconds ( 1 ))
. sendKeys ( "abc" )
. perform ()
val duration = System . currentTimeMillis () - start
Assertions . assertTrue ( duration > 2000 )
Assertions . assertTrue ( duration < 4000 )
}
@Test
fun releasesAll () {
driver . get ( "https://www.selenium.dev/selenium/web/mouse_interaction.html" )
val clickable = driver . findElement ( By . id ( "clickable" ))
val actions = Actions ( driver )
actions . clickAndHold ( clickable )
. keyDown ( Keys . SHIFT )
. sendKeys ( "a" )
. perform ()
( driver as RemoteWebDriver ). resetInputState ()
actions . sendKeys ( "a" ). perform ()
Assertions . assertEquals ( "A" , clickable . getAttribute ( "value" ). get ( 0 ). toString ())
Assertions . assertEquals ( "a" , clickable . getAttribute ( "value" ). get ( 1 ). toString ())
}
}
Uma representação de qualquer dispositivo de entrada de teclado para interagir com uma página da web.
Uma representação de qualquer dispositivo de ponteiro para interagir com uma página da web.
Uma representação de uma entrada de ponteiro do tipo caneta stylus para interagir com uma página da web.
“Uma representação de um dispositivo de entrada de roda de rolagem para interagir com uma página da web.”