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 ();
Show full example 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 ()
Show full example 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 ();
Show full example 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
Show full example # 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 clickable = await driver . findElement ( By . id ( 'clickable' ))
await driver . actions ()
. move ({ origin : clickable })
. pause ( 1000 )
. press ()
. pause ( 1000 )
. sendKeys ( 'abc' )
. perform ()
Show full example const { By , Key , Browser , Builder } = require ( 'selenium-webdriver' )
const assert = require ( 'assert' )
describe ( 'Actions API - Pause and Release All Actions' , function () {
let driver
before ( async function () {
driver = await new Builder (). forBrowser ( 'chrome' ). build ();
})
after ( async () => await 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 ))
})
})
val clickable = driver . findElement ( By . id ( "clickable" ))
Actions ( driver )
. moveToElement ( clickable )
. pause ( Duration . ofSeconds ( 1 ))
. clickAndHold ()
. pause ( Duration . ofSeconds ( 1 ))
. sendKeys ( "abc" )
. perform ()
Show full example 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 ();
Show full example 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 ()
Show full example 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 ();
Show full example 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
Show full example # 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
await driver . actions (). clear ()
Show full example const { By , Key , Browser , Builder } = require ( 'selenium-webdriver' )
const assert = require ( 'assert' )
describe ( 'Actions API - Pause and Release All Actions' , function () {
let driver
before ( async function () {
driver = await new Builder (). forBrowser ( 'chrome' ). build ();
})
after ( async () => await 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 ))
})
})
( driver as RemoteWebDriver ). resetInputState ()
Show full example 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 ())
}
}
1 - Ações de Teclado Uma representação de qualquer dispositivo de entrada de teclado para interagir com uma página da web.
Existem apenas 2 ações que podem ser realizadas com um teclado: pressionar uma tecla e liberar uma tecla pressionada. Além de suportar caracteres ASCII, cada tecla do teclado possui uma representação que pode ser pressionada ou liberada em sequências designadas.
Chaves Além das teclas representadas pelo Unicode regular, valores Unicode foram atribuídos a outras teclas de teclado para uso com o Selenium. Cada linguagem tem sua própria maneira de fazer referência a essas teclas; a lista completa pode ser encontrada
aqui .
Java
Python
CSharp
Ruby
JavaScript
Kotlin Use the [Java Keys enum](https://github.com/SeleniumHQ/selenium/blob/selenium-4.2.0/java/src/org/openqa/selenium/Keys.java#L28)
Use the [Python Keys class](https://github.com/SeleniumHQ/selenium/blob/selenium-4.2.0/py/selenium/webdriver/common/keys.py#L23)
Use the [.NET static Keys class](https://github.com/SeleniumHQ/selenium/blob/selenium-4.2.0/dotnet/src/webdriver/Keys.cs#L28)
Use the [Ruby KEYS constant](https://github.com/SeleniumHQ/selenium/blob/selenium-4.2.0/rb/lib/selenium/webdriver/common/keys.rb#L28)
Use the [JavaScript KEYS constant](https://github.com/SeleniumHQ/selenium/blob/selenium-4.2.0/javascript/node/selenium-webdriver/lib/input.js#L44)
Use the [Java Keys enum](https://github.com/SeleniumHQ/selenium/blob/selenium-4.2.0/java/src/org/openqa/selenium/Keys.java#L28)
Pressione a tecla
Java
Python
CSharp
Ruby
JavaScript
Kotlin new Actions ( driver )
. keyDown ( Keys . SHIFT )
. sendKeys ( "a" )
. perform ();
Show full example 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.Platform ;
import org.openqa.selenium.WebElement ;
import org.openqa.selenium.interactions.Actions ;
public class KeysTest extends BaseChromeTest {
@Test
public void keyDown () {
driver . get ( "https://www.selenium.dev/selenium/web/single_text_input.html" );
new Actions ( driver )
. keyDown ( Keys . SHIFT )
. sendKeys ( "a" )
. perform ();
WebElement textField = driver . findElement ( By . id ( "textInput" ));
Assertions . assertEquals ( "A" , textField . getAttribute ( "value" ));
}
@Test
public void keyUp () {
driver . get ( "https://www.selenium.dev/selenium/web/single_text_input.html" );
new Actions ( driver )
. keyDown ( Keys . SHIFT )
. sendKeys ( "a" )
. keyUp ( Keys . SHIFT )
. sendKeys ( "b" )
. perform ();
WebElement textField = driver . findElement ( By . id ( "textInput" ));
Assertions . assertEquals ( "Ab" , textField . getAttribute ( "value" ));
}
@Test
public void sendKeysToActiveElement () {
driver . get ( "https://www.selenium.dev/selenium/web/single_text_input.html" );
new Actions ( driver )
. sendKeys ( "abc" )
. perform ();
WebElement textField = driver . findElement ( By . id ( "textInput" ));
Assertions . assertEquals ( "abc" , textField . getAttribute ( "value" ));
}
@Test
public void sendKeysToDesignatedElement () {
driver . get ( "https://www.selenium.dev/selenium/web/single_text_input.html" );
driver . findElement ( By . tagName ( "body" )). click ();
WebElement textField = driver . findElement ( By . id ( "textInput" ));
new Actions ( driver )
. sendKeys ( textField , "Selenium!" )
. perform ();
Assertions . assertEquals ( "Selenium!" , textField . getAttribute ( "value" ));
}
@Test
public void copyAndPaste () {
driver . get ( "https://www.selenium.dev/selenium/web/single_text_input.html" );
Keys cmdCtrl = Platform . getCurrent (). is ( Platform . MAC ) ? Keys . COMMAND : Keys . CONTROL ;
WebElement textField = driver . findElement ( By . id ( "textInput" ));
new Actions ( driver )
. sendKeys ( textField , "Selenium!" )
. sendKeys ( Keys . ARROW_LEFT )
. keyDown ( Keys . SHIFT )
. sendKeys ( Keys . ARROW_UP )
. keyUp ( Keys . SHIFT )
. keyDown ( cmdCtrl )
. sendKeys ( "xvv" )
. keyUp ( cmdCtrl )
. perform ();
Assertions . assertEquals ( "SeleniumSelenium!" , textField . getAttribute ( "value" ));
}
}
ActionChains ( driver ) \
. key_down ( Keys . SHIFT ) \
. send_keys ( "abc" ) \
. perform ()
Show full example import sys
from selenium.webdriver import Keys , ActionChains
from selenium.webdriver.common.by import By
def test_key_down ( driver ):
driver . get ( 'https://selenium.dev/selenium/web/single_text_input.html' )
ActionChains ( driver ) \
. key_down ( Keys . SHIFT ) \
. send_keys ( "abc" ) \
. perform ()
assert driver . find_element ( By . ID , "textInput" ) . get_attribute ( 'value' ) == "ABC"
def test_key_up ( driver ):
driver . get ( 'https://selenium.dev/selenium/web/single_text_input.html' )
ActionChains ( driver ) \
. key_down ( Keys . SHIFT ) \
. send_keys ( "a" ) \
. key_up ( Keys . SHIFT ) \
. send_keys ( "b" ) \
. perform ()
assert driver . find_element ( By . ID , "textInput" ) . get_attribute ( 'value' ) == "Ab"
def test_send_keys_to_active_element ( driver ):
driver . get ( 'https://selenium.dev/selenium/web/single_text_input.html' )
ActionChains ( driver ) \
. send_keys ( "abc" ) \
. perform ()
assert driver . find_element ( By . ID , "textInput" ) . get_attribute ( 'value' ) == "abc"
def test_send_keys_to_designated_element ( driver ):
driver . get ( 'https://selenium.dev/selenium/web/single_text_input.html' )
driver . find_element ( By . TAG_NAME , "body" ) . click ()
text_input = driver . find_element ( By . ID , "textInput" )
ActionChains ( driver ) \
. send_keys_to_element ( text_input , "abc" ) \
. perform ()
assert driver . find_element ( By . ID , "textInput" ) . get_attribute ( 'value' ) == "abc"
def test_copy_and_paste ( firefox_driver ):
driver = firefox_driver
driver . get ( 'https://selenium.dev/selenium/web/single_text_input.html' )
cmd_ctrl = Keys . COMMAND if sys . platform == 'darwin' else Keys . CONTROL
ActionChains ( driver ) \
. send_keys ( "Selenium!" ) \
. send_keys ( Keys . ARROW_LEFT ) \
. key_down ( Keys . SHIFT ) \
. send_keys ( Keys . ARROW_UP ) \
. key_up ( Keys . SHIFT ) \
. key_down ( cmd_ctrl ) \
. send_keys ( "xvv" ) \
. key_up ( cmd_ctrl ) \
. perform ()
assert driver . find_element ( By . ID , "textInput" ) . get_attribute ( 'value' ) == "SeleniumSelenium!"
. KeyDown ( Keys . Shift )
. SendKeys ( "a" )
. Perform ();
Show full example using System ;
using Microsoft.VisualStudio.TestTools.UnitTesting ;
using OpenQA.Selenium ;
using OpenQA.Selenium.Interactions ;
namespace SeleniumDocs.ActionsAPI
{
[TestClass]
public class KeysTest : BaseFirefoxTest
{
[TestMethod]
public void KeyDown ()
{
driver . Url = "https://selenium.dev/selenium/web/single_text_input.html" ;
new Actions ( driver )
. KeyDown ( Keys . Shift )
. SendKeys ( "a" )
. Perform ();
IWebElement textField = driver . FindElement ( By . Id ( "textInput" ));
Assert . AreEqual ( "A" , textField . GetAttribute ( "value" ));
}
[TestMethod]
public void KeyUp ()
{
driver . Url = "https://selenium.dev/selenium/web/single_text_input.html" ;
new Actions ( driver )
. KeyDown ( Keys . Shift )
. SendKeys ( "a" )
. KeyUp ( Keys . Shift )
. SendKeys ( "b" )
. Perform ();
IWebElement textField = driver . FindElement ( By . Id ( "textInput" ));
Assert . AreEqual ( "Ab" , textField . GetAttribute ( "value" ));
}
[TestMethod]
public void SendKeysToActiveElement ()
{
driver . Url = "https://selenium.dev/selenium/web/single_text_input.html" ;
new Actions ( driver )
. SendKeys ( "abc" )
. Perform ();
IWebElement textField = driver . FindElement ( By . Id ( "textInput" ));
Assert . AreEqual ( "abc" , textField . GetAttribute ( "value" ));
}
[TestMethod]
public void SendKeysToDesignatedElement ()
{
driver . Url = "https://selenium.dev/selenium/web/single_text_input.html" ;
driver . FindElement ( By . TagName ( "body" )). Click ();
IWebElement textField = driver . FindElement ( By . Id ( "textInput" ));
new Actions ( driver )
. SendKeys ( textField , "abc" )
. Perform ();
Assert . AreEqual ( "abc" , textField . GetAttribute ( "value" ));
}
[TestMethod]
public void CopyAndPaste ()
{
driver . Url = "https://selenium.dev/selenium/web/single_text_input.html" ;
var capabilities = (( WebDriver ) driver ). Capabilities ;
String platformName = ( string ) capabilities . GetCapability ( "platformName" );
String cmdCtrl = platformName . Contains ( "mac" ) ? Keys . Command : Keys . Control ;
new Actions ( driver )
. SendKeys ( "Selenium!" )
. SendKeys ( Keys . ArrowLeft )
. KeyDown ( Keys . Shift )
. SendKeys ( Keys . ArrowUp )
. KeyUp ( Keys . Shift )
. KeyDown ( cmdCtrl )
. SendKeys ( "xvv" )
. KeyUp ( cmdCtrl )
. Perform ();
IWebElement textField = driver . FindElement ( By . Id ( "textInput" ));
Assert . AreEqual ( "SeleniumSelenium!" , textField . GetAttribute ( "value" ));
}
}
}
driver . action
. key_down ( :shift )
. send_keys ( 'a' )
. perform
Show full example # frozen_string_literal: true
require 'spec_helper'
RSpec . describe 'Keys' do
let ( :driver ) { start_session }
let ( :wait ) { Selenium :: WebDriver :: Wait . new ( timeout : 2 ) }
it 'key down' do
driver . get 'https://www.selenium.dev/selenium/web/single_text_input.html'
wait . until { driver . find_element ( id : 'textInput' ) . attribute ( 'autofocus' ) }
driver . action
. key_down ( :shift )
. send_keys ( 'a' )
. perform
expect ( driver . find_element ( id : 'textInput' ) . attribute ( 'value' )) . to eq 'A'
end
it 'key up' do
driver . get 'https://www.selenium.dev/selenium/web/single_text_input.html'
wait . until { driver . find_element ( id : 'textInput' ) . attribute ( 'autofocus' ) }
driver . action
. key_down ( :shift )
. send_keys ( 'a' )
. key_up ( :shift )
. send_keys ( 'b' )
. perform
expect ( driver . find_element ( id : 'textInput' ) . attribute ( 'value' )) . to eq 'Ab'
end
it 'sends keys to active element' do
driver . get 'https://www.selenium.dev/selenium/web/single_text_input.html'
wait . until { driver . find_element ( id : 'textInput' ) . attribute ( 'autofocus' ) }
driver . action
. send_keys ( 'abc' )
. perform
expect ( driver . find_element ( id : 'textInput' ) . attribute ( 'value' )) . to eq 'abc'
end
it 'sends keys to designated element' do
driver . get 'https://www.selenium.dev/selenium/web/single_text_input.html'
driver . find_element ( tag_name : 'body' ) . click
wait . until { driver . find_element ( id : 'textInput' ) . attribute ( 'autofocus' ) }
text_field = driver . find_element ( id : 'textInput' )
driver . action
. send_keys ( text_field , 'Selenium!' )
. perform
expect ( text_field . attribute ( 'value' )) . to eq 'Selenium!'
end
it 'copy and paste' do
driver . get 'https://www.selenium.dev/selenium/web/single_text_input.html'
wait . until { driver . find_element ( id : 'textInput' ) . attribute ( 'autofocus' ) }
cmd_ctrl = driver . capabilities . platform_name . include? ( 'mac' ) ? :command : :control
driver . action
. send_keys ( 'Selenium!' )
. send_keys ( :arrow_left )
. key_down ( :shift )
. send_keys ( :arrow_up )
. key_up ( :shift )
. key_down ( cmd_ctrl )
. send_keys ( 'xvv' )
. key_up ( cmd_ctrl )
. perform
expect ( driver . find_element ( id : 'textInput' ) . attribute ( 'value' )) . to eq 'SeleniumSelenium!'
end
end
await driver . actions ()
. keyDown ( Key . SHIFT )
. sendKeys ( 'a' )
. perform ()
Show full example const { By , Key , Browser , Builder } = require ( 'selenium-webdriver' )
const assert = require ( 'assert' )
const { platform } = require ( 'node:process' )
describe ( 'Keyboard Action - Keys test' , function () {
let driver
before ( async function () {
driver = await new Builder (). forBrowser ( 'chrome' ). build ();
})
after ( async () => await driver . quit ())
it ( 'KeyDown' , async function () {
await driver . get ( 'https://www.selenium.dev/selenium/web/single_text_input.html' )
await driver . actions ()
. keyDown ( Key . SHIFT )
. sendKeys ( 'a' )
. perform ()
const textField = driver . findElement ( By . id ( 'textInput' ))
assert . deepStrictEqual ( await textField . getAttribute ( 'value' ), 'A' )
})
it ( 'KeyUp' , async function () {
await driver . get ( 'https://www.selenium.dev/selenium/web/single_text_input.html' )
const textField = driver . findElement ( By . id ( 'textInput' ))
await textField . click ()
await driver . actions ()
. keyDown ( Key . SHIFT )
. sendKeys ( 'a' )
. keyUp ( Key . SHIFT )
. sendKeys ( 'b' )
. perform ()
assert . deepStrictEqual ( await textField . getAttribute ( 'value' ), 'Ab' )
})
it ( 'sendKeys' , async function () {
await driver . get ( 'https://www.selenium.dev/selenium/web/single_text_input.html' )
const textField = driver . findElement ( By . id ( 'textInput' ))
await textField . click ()
await driver . actions ()
. sendKeys ( 'abc' )
. perform ()
assert . deepStrictEqual ( await textField . getAttribute ( 'value' ), 'abc' )
})
it ( 'Designated Element' , async function () {
await driver . get ( 'https://www.selenium.dev/selenium/web/single_text_input.html' )
await driver . findElement ( By . css ( 'body' )). click ()
const textField = await driver . findElement ( By . id ( 'textInput' ))
await driver . actions ()
. sendKeys ( textField , 'abc' )
. perform ()
assert . deepStrictEqual ( await textField . getAttribute ( 'value' ), 'abc' )
})
it ( 'Copy and Paste' , async function () {
await driver . get ( 'https://www.selenium.dev/selenium/web/single_text_input.html' )
const textField = await driver . findElement ( By . id ( 'textInput' ))
const cmdCtrl = platform . includes ( 'darwin' ) ? Key . COMMAND : Key . CONTROL
await driver . actions ()
. click ( textField )
. sendKeys ( 'Selenium!' )
. sendKeys ( Key . ARROW_LEFT )
. keyDown ( Key . SHIFT )
. sendKeys ( Key . ARROW_UP )
. keyUp ( Key . SHIFT )
. keyDown ( cmdCtrl )
. sendKeys ( 'xvv' )
. keyUp ( cmdCtrl )
. perform ()
assert . deepStrictEqual ( await textField . getAttribute ( 'value' ), 'SeleniumSelenium!' )
})
})
Actions ( driver )
. keyDown ( Keys . SHIFT )
. sendKeys ( "a" )
. perform ()
Show full example 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.HasCapabilities
import org.openqa.selenium.Keys
import org.openqa.selenium.Platform
import org.openqa.selenium.WebElement
import org.openqa.selenium.interactions.Actions
class KeysTest : BaseTest () {
@Test
fun keyDown () {
driver . get ( "https://www.selenium.dev/selenium/web/single_text_input.html" )
Actions ( driver )
. keyDown ( Keys . SHIFT )
. sendKeys ( "a" )
. perform ()
val textField = driver . findElement ( By . id ( "textInput" ))
Assertions . assertEquals ( "A" , textField . getAttribute ( "value" ))
}
@Test
fun keyUp () {
driver . get ( "https://www.selenium.dev/selenium/web/single_text_input.html" )
Actions ( driver )
. keyDown ( Keys . SHIFT )
. sendKeys ( "a" )
. keyUp ( Keys . SHIFT )
. sendKeys ( "b" )
. perform ()
val textField = driver . findElement ( By . id ( "textInput" ))
Assertions . assertEquals ( "Ab" , textField . getAttribute ( "value" ))
}
@Test
fun sendKeysToActiveElement () {
driver . get ( "https://www.selenium.dev/selenium/web/single_text_input.html" )
Actions ( driver )
. sendKeys ( "abc" )
. perform ()
val textField = driver . findElement ( By . id ( "textInput" ))
Assertions . assertEquals ( "abc" , textField . getAttribute ( "value" ))
}
@Test
fun sendKeysToDesignatedElement () {
driver . get ( "https://www.selenium.dev/selenium/web/single_text_input.html" )
driver . findElement ( By . tagName ( "body" )). click ()
val textField = driver . findElement ( By . id ( "textInput" ))
Actions ( driver )
. sendKeys ( textField , "Selenium!" )
. perform ()
Assertions . assertEquals ( "Selenium!" , textField . getAttribute ( "value" ))
}
@Test
fun copyAndPaste () {
driver . get ( "https://www.selenium.dev/selenium/web/single_text_input.html" )
val platformName = ( driver as HasCapabilities ). getCapabilities (). getPlatformName ()
val cmdCtrl = if ( platformName == Platform . MAC ) Keys . COMMAND else Keys . CONTROL
val textField = driver . findElement ( By . id ( "textInput" ))
Actions ( driver )
. sendKeys ( textField , "Selenium!" )
. sendKeys ( Keys . ARROW_LEFT )
. keyDown ( Keys . SHIFT )
. sendKeys ( Keys . ARROW_UP )
. keyUp ( Keys . SHIFT )
. keyDown ( cmdCtrl )
. sendKeys ( "xvv" )
. keyUp ( cmdCtrl )
. perform ()
Assertions . assertEquals ( "SeleniumSelenium!" , textField . getAttribute ( "value" ))
}
}
Liberar a tecla
Java
Python
CSharp
Ruby
JavaScript
Kotlin new Actions ( driver )
. keyDown ( Keys . SHIFT )
. sendKeys ( "a" )
. keyUp ( Keys . SHIFT )
. sendKeys ( "b" )
. perform ();
Show full example 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.Platform ;
import org.openqa.selenium.WebElement ;
import org.openqa.selenium.interactions.Actions ;
public class KeysTest extends BaseChromeTest {
@Test
public void keyDown () {
driver . get ( "https://www.selenium.dev/selenium/web/single_text_input.html" );
new Actions ( driver )
. keyDown ( Keys . SHIFT )
. sendKeys ( "a" )
. perform ();
WebElement textField = driver . findElement ( By . id ( "textInput" ));
Assertions . assertEquals ( "A" , textField . getAttribute ( "value" ));
}
@Test
public void keyUp () {
driver . get ( "https://www.selenium.dev/selenium/web/single_text_input.html" );
new Actions ( driver )
. keyDown ( Keys . SHIFT )
. sendKeys ( "a" )
. keyUp ( Keys . SHIFT )
. sendKeys ( "b" )
. perform ();
WebElement textField = driver . findElement ( By . id ( "textInput" ));
Assertions . assertEquals ( "Ab" , textField . getAttribute ( "value" ));
}
@Test
public void sendKeysToActiveElement () {
driver . get ( "https://www.selenium.dev/selenium/web/single_text_input.html" );
new Actions ( driver )
. sendKeys ( "abc" )
. perform ();
WebElement textField = driver . findElement ( By . id ( "textInput" ));
Assertions . assertEquals ( "abc" , textField . getAttribute ( "value" ));
}
@Test
public void sendKeysToDesignatedElement () {
driver . get ( "https://www.selenium.dev/selenium/web/single_text_input.html" );
driver . findElement ( By . tagName ( "body" )). click ();
WebElement textField = driver . findElement ( By . id ( "textInput" ));
new Actions ( driver )
. sendKeys ( textField , "Selenium!" )
. perform ();
Assertions . assertEquals ( "Selenium!" , textField . getAttribute ( "value" ));
}
@Test
public void copyAndPaste () {
driver . get ( "https://www.selenium.dev/selenium/web/single_text_input.html" );
Keys cmdCtrl = Platform . getCurrent (). is ( Platform . MAC ) ? Keys . COMMAND : Keys . CONTROL ;
WebElement textField = driver . findElement ( By . id ( "textInput" ));
new Actions ( driver )
. sendKeys ( textField , "Selenium!" )
. sendKeys ( Keys . ARROW_LEFT )
. keyDown ( Keys . SHIFT )
. sendKeys ( Keys . ARROW_UP )
. keyUp ( Keys . SHIFT )
. keyDown ( cmdCtrl )
. sendKeys ( "xvv" )
. keyUp ( cmdCtrl )
. perform ();
Assertions . assertEquals ( "SeleniumSelenium!" , textField . getAttribute ( "value" ));
}
}
ActionChains ( driver ) \
. key_down ( Keys . SHIFT ) \
. send_keys ( "a" ) \
. key_up ( Keys . SHIFT ) \
. send_keys ( "b" ) \
. perform ()
Show full example import sys
from selenium.webdriver import Keys , ActionChains
from selenium.webdriver.common.by import By
def test_key_down ( driver ):
driver . get ( 'https://selenium.dev/selenium/web/single_text_input.html' )
ActionChains ( driver ) \
. key_down ( Keys . SHIFT ) \
. send_keys ( "abc" ) \
. perform ()
assert driver . find_element ( By . ID , "textInput" ) . get_attribute ( 'value' ) == "ABC"
def test_key_up ( driver ):
driver . get ( 'https://selenium.dev/selenium/web/single_text_input.html' )
ActionChains ( driver ) \
. key_down ( Keys . SHIFT ) \
. send_keys ( "a" ) \
. key_up ( Keys . SHIFT ) \
. send_keys ( "b" ) \
. perform ()
assert driver . find_element ( By . ID , "textInput" ) . get_attribute ( 'value' ) == "Ab"
def test_send_keys_to_active_element ( driver ):
driver . get ( 'https://selenium.dev/selenium/web/single_text_input.html' )
ActionChains ( driver ) \
. send_keys ( "abc" ) \
. perform ()
assert driver . find_element ( By . ID , "textInput" ) . get_attribute ( 'value' ) == "abc"
def test_send_keys_to_designated_element ( driver ):
driver . get ( 'https://selenium.dev/selenium/web/single_text_input.html' )
driver . find_element ( By . TAG_NAME , "body" ) . click ()
text_input = driver . find_element ( By . ID , "textInput" )
ActionChains ( driver ) \
. send_keys_to_element ( text_input , "abc" ) \
. perform ()
assert driver . find_element ( By . ID , "textInput" ) . get_attribute ( 'value' ) == "abc"
def test_copy_and_paste ( firefox_driver ):
driver = firefox_driver
driver . get ( 'https://selenium.dev/selenium/web/single_text_input.html' )
cmd_ctrl = Keys . COMMAND if sys . platform == 'darwin' else Keys . CONTROL
ActionChains ( driver ) \
. send_keys ( "Selenium!" ) \
. send_keys ( Keys . ARROW_LEFT ) \
. key_down ( Keys . SHIFT ) \
. send_keys ( Keys . ARROW_UP ) \
. key_up ( Keys . SHIFT ) \
. key_down ( cmd_ctrl ) \
. send_keys ( "xvv" ) \
. key_up ( cmd_ctrl ) \
. perform ()
assert driver . find_element ( By . ID , "textInput" ) . get_attribute ( 'value' ) == "SeleniumSelenium!"
new Actions ( driver )
. KeyDown ( Keys . Shift )
. SendKeys ( "a" )
. KeyUp ( Keys . Shift )
. SendKeys ( "b" )
. Perform ();
Show full example using System ;
using Microsoft.VisualStudio.TestTools.UnitTesting ;
using OpenQA.Selenium ;
using OpenQA.Selenium.Interactions ;
namespace SeleniumDocs.ActionsAPI
{
[TestClass]
public class KeysTest : BaseFirefoxTest
{
[TestMethod]
public void KeyDown ()
{
driver . Url = "https://selenium.dev/selenium/web/single_text_input.html" ;
new Actions ( driver )
. KeyDown ( Keys . Shift )
. SendKeys ( "a" )
. Perform ();
IWebElement textField = driver . FindElement ( By . Id ( "textInput" ));
Assert . AreEqual ( "A" , textField . GetAttribute ( "value" ));
}
[TestMethod]
public void KeyUp ()
{
driver . Url = "https://selenium.dev/selenium/web/single_text_input.html" ;
new Actions ( driver )
. KeyDown ( Keys . Shift )
. SendKeys ( "a" )
. KeyUp ( Keys . Shift )
. SendKeys ( "b" )
. Perform ();
IWebElement textField = driver . FindElement ( By . Id ( "textInput" ));
Assert . AreEqual ( "Ab" , textField . GetAttribute ( "value" ));
}
[TestMethod]
public void SendKeysToActiveElement ()
{
driver . Url = "https://selenium.dev/selenium/web/single_text_input.html" ;
new Actions ( driver )
. SendKeys ( "abc" )
. Perform ();
IWebElement textField = driver . FindElement ( By . Id ( "textInput" ));
Assert . AreEqual ( "abc" , textField . GetAttribute ( "value" ));
}
[TestMethod]
public void SendKeysToDesignatedElement ()
{
driver . Url = "https://selenium.dev/selenium/web/single_text_input.html" ;
driver . FindElement ( By . TagName ( "body" )). Click ();
IWebElement textField = driver . FindElement ( By . Id ( "textInput" ));
new Actions ( driver )
. SendKeys ( textField , "abc" )
. Perform ();
Assert . AreEqual ( "abc" , textField . GetAttribute ( "value" ));
}
[TestMethod]
public void CopyAndPaste ()
{
driver . Url = "https://selenium.dev/selenium/web/single_text_input.html" ;
var capabilities = (( WebDriver ) driver ). Capabilities ;
String platformName = ( string ) capabilities . GetCapability ( "platformName" );
String cmdCtrl = platformName . Contains ( "mac" ) ? Keys . Command : Keys . Control ;
new Actions ( driver )
. SendKeys ( "Selenium!" )
. SendKeys ( Keys . ArrowLeft )
. KeyDown ( Keys . Shift )
. SendKeys ( Keys . ArrowUp )
. KeyUp ( Keys . Shift )
. KeyDown ( cmdCtrl )
. SendKeys ( "xvv" )
. KeyUp ( cmdCtrl )
. Perform ();
IWebElement textField = driver . FindElement ( By . Id ( "textInput" ));
Assert . AreEqual ( "SeleniumSelenium!" , textField . GetAttribute ( "value" ));
}
}
}
driver . action
. key_down ( :shift )
. send_keys ( 'a' )
. key_up ( :shift )
. send_keys ( 'b' )
. perform
Show full example # frozen_string_literal: true
require 'spec_helper'
RSpec . describe 'Keys' do
let ( :driver ) { start_session }
let ( :wait ) { Selenium :: WebDriver :: Wait . new ( timeout : 2 ) }
it 'key down' do
driver . get 'https://www.selenium.dev/selenium/web/single_text_input.html'
wait . until { driver . find_element ( id : 'textInput' ) . attribute ( 'autofocus' ) }
driver . action
. key_down ( :shift )
. send_keys ( 'a' )
. perform
expect ( driver . find_element ( id : 'textInput' ) . attribute ( 'value' )) . to eq 'A'
end
it 'key up' do
driver . get 'https://www.selenium.dev/selenium/web/single_text_input.html'
wait . until { driver . find_element ( id : 'textInput' ) . attribute ( 'autofocus' ) }
driver . action
. key_down ( :shift )
. send_keys ( 'a' )
. key_up ( :shift )
. send_keys ( 'b' )
. perform
expect ( driver . find_element ( id : 'textInput' ) . attribute ( 'value' )) . to eq 'Ab'
end
it 'sends keys to active element' do
driver . get 'https://www.selenium.dev/selenium/web/single_text_input.html'
wait . until { driver . find_element ( id : 'textInput' ) . attribute ( 'autofocus' ) }
driver . action
. send_keys ( 'abc' )
. perform
expect ( driver . find_element ( id : 'textInput' ) . attribute ( 'value' )) . to eq 'abc'
end
it 'sends keys to designated element' do
driver . get 'https://www.selenium.dev/selenium/web/single_text_input.html'
driver . find_element ( tag_name : 'body' ) . click
wait . until { driver . find_element ( id : 'textInput' ) . attribute ( 'autofocus' ) }
text_field = driver . find_element ( id : 'textInput' )
driver . action
. send_keys ( text_field , 'Selenium!' )
. perform
expect ( text_field . attribute ( 'value' )) . to eq 'Selenium!'
end
it 'copy and paste' do
driver . get 'https://www.selenium.dev/selenium/web/single_text_input.html'
wait . until { driver . find_element ( id : 'textInput' ) . attribute ( 'autofocus' ) }
cmd_ctrl = driver . capabilities . platform_name . include? ( 'mac' ) ? :command : :control
driver . action
. send_keys ( 'Selenium!' )
. send_keys ( :arrow_left )
. key_down ( :shift )
. send_keys ( :arrow_up )
. key_up ( :shift )
. key_down ( cmd_ctrl )
. send_keys ( 'xvv' )
. key_up ( cmd_ctrl )
. perform
expect ( driver . find_element ( id : 'textInput' ) . attribute ( 'value' )) . to eq 'SeleniumSelenium!'
end
end
await driver . actions ()
. keyDown ( Key . SHIFT )
. sendKeys ( 'a' )
. keyUp ( Key . SHIFT )
. sendKeys ( 'b' )
. perform ()
Show full example const { By , Key , Browser , Builder } = require ( 'selenium-webdriver' )
const assert = require ( 'assert' )
const { platform } = require ( 'node:process' )
describe ( 'Keyboard Action - Keys test' , function () {
let driver
before ( async function () {
driver = await new Builder (). forBrowser ( 'chrome' ). build ();
})
after ( async () => await driver . quit ())
it ( 'KeyDown' , async function () {
await driver . get ( 'https://www.selenium.dev/selenium/web/single_text_input.html' )
await driver . actions ()
. keyDown ( Key . SHIFT )
. sendKeys ( 'a' )
. perform ()
const textField = driver . findElement ( By . id ( 'textInput' ))
assert . deepStrictEqual ( await textField . getAttribute ( 'value' ), 'A' )
})
it ( 'KeyUp' , async function () {
await driver . get ( 'https://www.selenium.dev/selenium/web/single_text_input.html' )
const textField = driver . findElement ( By . id ( 'textInput' ))
await textField . click ()
await driver . actions ()
. keyDown ( Key . SHIFT )
. sendKeys ( 'a' )
. keyUp ( Key . SHIFT )
. sendKeys ( 'b' )
. perform ()
assert . deepStrictEqual ( await textField . getAttribute ( 'value' ), 'Ab' )
})
it ( 'sendKeys' , async function () {
await driver . get ( 'https://www.selenium.dev/selenium/web/single_text_input.html' )
const textField = driver . findElement ( By . id ( 'textInput' ))
await textField . click ()
await driver . actions ()
. sendKeys ( 'abc' )
. perform ()
assert . deepStrictEqual ( await textField . getAttribute ( 'value' ), 'abc' )
})
it ( 'Designated Element' , async function () {
await driver . get ( 'https://www.selenium.dev/selenium/web/single_text_input.html' )
await driver . findElement ( By . css ( 'body' )). click ()
const textField = await driver . findElement ( By . id ( 'textInput' ))
await driver . actions ()
. sendKeys ( textField , 'abc' )
. perform ()
assert . deepStrictEqual ( await textField . getAttribute ( 'value' ), 'abc' )
})
it ( 'Copy and Paste' , async function () {
await driver . get ( 'https://www.selenium.dev/selenium/web/single_text_input.html' )
const textField = await driver . findElement ( By . id ( 'textInput' ))
const cmdCtrl = platform . includes ( 'darwin' ) ? Key . COMMAND : Key . CONTROL
await driver . actions ()
. click ( textField )
. sendKeys ( 'Selenium!' )
. sendKeys ( Key . ARROW_LEFT )
. keyDown ( Key . SHIFT )
. sendKeys ( Key . ARROW_UP )
. keyUp ( Key . SHIFT )
. keyDown ( cmdCtrl )
. sendKeys ( 'xvv' )
. keyUp ( cmdCtrl )
. perform ()
assert . deepStrictEqual ( await textField . getAttribute ( 'value' ), 'SeleniumSelenium!' )
})
})
Actions ( driver )
. keyDown ( Keys . SHIFT )
. sendKeys ( "a" )
. keyUp ( Keys . SHIFT )
. sendKeys ( "b" )
. perform ()
Show full example 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.HasCapabilities
import org.openqa.selenium.Keys
import org.openqa.selenium.Platform
import org.openqa.selenium.WebElement
import org.openqa.selenium.interactions.Actions
class KeysTest : BaseTest () {
@Test
fun keyDown () {
driver . get ( "https://www.selenium.dev/selenium/web/single_text_input.html" )
Actions ( driver )
. keyDown ( Keys . SHIFT )
. sendKeys ( "a" )
. perform ()
val textField = driver . findElement ( By . id ( "textInput" ))
Assertions . assertEquals ( "A" , textField . getAttribute ( "value" ))
}
@Test
fun keyUp () {
driver . get ( "https://www.selenium.dev/selenium/web/single_text_input.html" )
Actions ( driver )
. keyDown ( Keys . SHIFT )
. sendKeys ( "a" )
. keyUp ( Keys . SHIFT )
. sendKeys ( "b" )
. perform ()
val textField = driver . findElement ( By . id ( "textInput" ))
Assertions . assertEquals ( "Ab" , textField . getAttribute ( "value" ))
}
@Test
fun sendKeysToActiveElement () {
driver . get ( "https://www.selenium.dev/selenium/web/single_text_input.html" )
Actions ( driver )
. sendKeys ( "abc" )
. perform ()
val textField = driver . findElement ( By . id ( "textInput" ))
Assertions . assertEquals ( "abc" , textField . getAttribute ( "value" ))
}
@Test
fun sendKeysToDesignatedElement () {
driver . get ( "https://www.selenium.dev/selenium/web/single_text_input.html" )
driver . findElement ( By . tagName ( "body" )). click ()
val textField = driver . findElement ( By . id ( "textInput" ))
Actions ( driver )
. sendKeys ( textField , "Selenium!" )
. perform ()
Assertions . assertEquals ( "Selenium!" , textField . getAttribute ( "value" ))
}
@Test
fun copyAndPaste () {
driver . get ( "https://www.selenium.dev/selenium/web/single_text_input.html" )
val platformName = ( driver as HasCapabilities ). getCapabilities (). getPlatformName ()
val cmdCtrl = if ( platformName == Platform . MAC ) Keys . COMMAND else Keys . CONTROL
val textField = driver . findElement ( By . id ( "textInput" ))
Actions ( driver )
. sendKeys ( textField , "Selenium!" )
. sendKeys ( Keys . ARROW_LEFT )
. keyDown ( Keys . SHIFT )
. sendKeys ( Keys . ARROW_UP )
. keyUp ( Keys . SHIFT )
. keyDown ( cmdCtrl )
. sendKeys ( "xvv" )
. keyUp ( cmdCtrl )
. perform ()
Assertions . assertEquals ( "SeleniumSelenium!" , textField . getAttribute ( "value" ))
}
}
Enviar teclas This is a convenience method in the Actions API that combines keyDown and keyUp commands in one action.
Executing this command differs slightly from using the element method, but
primarily this gets used when needing to type multiple characters in the middle of other actions.
Elemento Ativo
Java
Python
CSharp
Ruby
JavaScript
Kotlin new Actions ( driver )
. sendKeys ( "abc" )
. perform ();
Show full example 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.Platform ;
import org.openqa.selenium.WebElement ;
import org.openqa.selenium.interactions.Actions ;
public class KeysTest extends BaseChromeTest {
@Test
public void keyDown () {
driver . get ( "https://www.selenium.dev/selenium/web/single_text_input.html" );
new Actions ( driver )
. keyDown ( Keys . SHIFT )
. sendKeys ( "a" )
. perform ();
WebElement textField = driver . findElement ( By . id ( "textInput" ));
Assertions . assertEquals ( "A" , textField . getAttribute ( "value" ));
}
@Test
public void keyUp () {
driver . get ( "https://www.selenium.dev/selenium/web/single_text_input.html" );
new Actions ( driver )
. keyDown ( Keys . SHIFT )
. sendKeys ( "a" )
. keyUp ( Keys . SHIFT )
. sendKeys ( "b" )
. perform ();
WebElement textField = driver . findElement ( By . id ( "textInput" ));
Assertions . assertEquals ( "Ab" , textField . getAttribute ( "value" ));
}
@Test
public void sendKeysToActiveElement () {
driver . get ( "https://www.selenium.dev/selenium/web/single_text_input.html" );
new Actions ( driver )
. sendKeys ( "abc" )
. perform ();
WebElement textField = driver . findElement ( By . id ( "textInput" ));
Assertions . assertEquals ( "abc" , textField . getAttribute ( "value" ));
}
@Test
public void sendKeysToDesignatedElement () {
driver . get ( "https://www.selenium.dev/selenium/web/single_text_input.html" );
driver . findElement ( By . tagName ( "body" )). click ();
WebElement textField = driver . findElement ( By . id ( "textInput" ));
new Actions ( driver )
. sendKeys ( textField , "Selenium!" )
. perform ();
Assertions . assertEquals ( "Selenium!" , textField . getAttribute ( "value" ));
}
@Test
public void copyAndPaste () {
driver . get ( "https://www.selenium.dev/selenium/web/single_text_input.html" );
Keys cmdCtrl = Platform . getCurrent (). is ( Platform . MAC ) ? Keys . COMMAND : Keys . CONTROL ;
WebElement textField = driver . findElement ( By . id ( "textInput" ));
new Actions ( driver )
. sendKeys ( textField , "Selenium!" )
. sendKeys ( Keys . ARROW_LEFT )
. keyDown ( Keys . SHIFT )
. sendKeys ( Keys . ARROW_UP )
. keyUp ( Keys . SHIFT )
. keyDown ( cmdCtrl )
. sendKeys ( "xvv" )
. keyUp ( cmdCtrl )
. perform ();
Assertions . assertEquals ( "SeleniumSelenium!" , textField . getAttribute ( "value" ));
}
}
ActionChains ( driver ) \
. send_keys ( "abc" ) \
. perform ()
Show full example import sys
from selenium.webdriver import Keys , ActionChains
from selenium.webdriver.common.by import By
def test_key_down ( driver ):
driver . get ( 'https://selenium.dev/selenium/web/single_text_input.html' )
ActionChains ( driver ) \
. key_down ( Keys . SHIFT ) \
. send_keys ( "abc" ) \
. perform ()
assert driver . find_element ( By . ID , "textInput" ) . get_attribute ( 'value' ) == "ABC"
def test_key_up ( driver ):
driver . get ( 'https://selenium.dev/selenium/web/single_text_input.html' )
ActionChains ( driver ) \
. key_down ( Keys . SHIFT ) \
. send_keys ( "a" ) \
. key_up ( Keys . SHIFT ) \
. send_keys ( "b" ) \
. perform ()
assert driver . find_element ( By . ID , "textInput" ) . get_attribute ( 'value' ) == "Ab"
def test_send_keys_to_active_element ( driver ):
driver . get ( 'https://selenium.dev/selenium/web/single_text_input.html' )
ActionChains ( driver ) \
. send_keys ( "abc" ) \
. perform ()
assert driver . find_element ( By . ID , "textInput" ) . get_attribute ( 'value' ) == "abc"
def test_send_keys_to_designated_element ( driver ):
driver . get ( 'https://selenium.dev/selenium/web/single_text_input.html' )
driver . find_element ( By . TAG_NAME , "body" ) . click ()
text_input = driver . find_element ( By . ID , "textInput" )
ActionChains ( driver ) \
. send_keys_to_element ( text_input , "abc" ) \
. perform ()
assert driver . find_element ( By . ID , "textInput" ) . get_attribute ( 'value' ) == "abc"
def test_copy_and_paste ( firefox_driver ):
driver = firefox_driver
driver . get ( 'https://selenium.dev/selenium/web/single_text_input.html' )
cmd_ctrl = Keys . COMMAND if sys . platform == 'darwin' else Keys . CONTROL
ActionChains ( driver ) \
. send_keys ( "Selenium!" ) \
. send_keys ( Keys . ARROW_LEFT ) \
. key_down ( Keys . SHIFT ) \
. send_keys ( Keys . ARROW_UP ) \
. key_up ( Keys . SHIFT ) \
. key_down ( cmd_ctrl ) \
. send_keys ( "xvv" ) \
. key_up ( cmd_ctrl ) \
. perform ()
assert driver . find_element ( By . ID , "textInput" ) . get_attribute ( 'value' ) == "SeleniumSelenium!"
new Actions ( driver )
. SendKeys ( "abc" )
Show full example using System ;
using Microsoft.VisualStudio.TestTools.UnitTesting ;
using OpenQA.Selenium ;
using OpenQA.Selenium.Interactions ;
namespace SeleniumDocs.ActionsAPI
{
[TestClass]
public class KeysTest : BaseFirefoxTest
{
[TestMethod]
public void KeyDown ()
{
driver . Url = "https://selenium.dev/selenium/web/single_text_input.html" ;
new Actions ( driver )
. KeyDown ( Keys . Shift )
. SendKeys ( "a" )
. Perform ();
IWebElement textField = driver . FindElement ( By . Id ( "textInput" ));
Assert . AreEqual ( "A" , textField . GetAttribute ( "value" ));
}
[TestMethod]
public void KeyUp ()
{
driver . Url = "https://selenium.dev/selenium/web/single_text_input.html" ;
new Actions ( driver )
. KeyDown ( Keys . Shift )
. SendKeys ( "a" )
. KeyUp ( Keys . Shift )
. SendKeys ( "b" )
. Perform ();
IWebElement textField = driver . FindElement ( By . Id ( "textInput" ));
Assert . AreEqual ( "Ab" , textField . GetAttribute ( "value" ));
}
[TestMethod]
public void SendKeysToActiveElement ()
{
driver . Url = "https://selenium.dev/selenium/web/single_text_input.html" ;
new Actions ( driver )
. SendKeys ( "abc" )
. Perform ();
IWebElement textField = driver . FindElement ( By . Id ( "textInput" ));
Assert . AreEqual ( "abc" , textField . GetAttribute ( "value" ));
}
[TestMethod]
public void SendKeysToDesignatedElement ()
{
driver . Url = "https://selenium.dev/selenium/web/single_text_input.html" ;
driver . FindElement ( By . TagName ( "body" )). Click ();
IWebElement textField = driver . FindElement ( By . Id ( "textInput" ));
new Actions ( driver )
. SendKeys ( textField , "abc" )
. Perform ();
Assert . AreEqual ( "abc" , textField . GetAttribute ( "value" ));
}
[TestMethod]
public void CopyAndPaste ()
{
driver . Url = "https://selenium.dev/selenium/web/single_text_input.html" ;
var capabilities = (( WebDriver ) driver ). Capabilities ;
String platformName = ( string ) capabilities . GetCapability ( "platformName" );
String cmdCtrl = platformName . Contains ( "mac" ) ? Keys . Command : Keys . Control ;
new Actions ( driver )
. SendKeys ( "Selenium!" )
. SendKeys ( Keys . ArrowLeft )
. KeyDown ( Keys . Shift )
. SendKeys ( Keys . ArrowUp )
. KeyUp ( Keys . Shift )
. KeyDown ( cmdCtrl )
. SendKeys ( "xvv" )
. KeyUp ( cmdCtrl )
. Perform ();
IWebElement textField = driver . FindElement ( By . Id ( "textInput" ));
Assert . AreEqual ( "SeleniumSelenium!" , textField . GetAttribute ( "value" ));
}
}
}
driver . action
. send_keys ( 'abc' )
. perform
Show full example # frozen_string_literal: true
require 'spec_helper'
RSpec . describe 'Keys' do
let ( :driver ) { start_session }
let ( :wait ) { Selenium :: WebDriver :: Wait . new ( timeout : 2 ) }
it 'key down' do
driver . get 'https://www.selenium.dev/selenium/web/single_text_input.html'
wait . until { driver . find_element ( id : 'textInput' ) . attribute ( 'autofocus' ) }
driver . action
. key_down ( :shift )
. send_keys ( 'a' )
. perform
expect ( driver . find_element ( id : 'textInput' ) . attribute ( 'value' )) . to eq 'A'
end
it 'key up' do
driver . get 'https://www.selenium.dev/selenium/web/single_text_input.html'
wait . until { driver . find_element ( id : 'textInput' ) . attribute ( 'autofocus' ) }
driver . action
. key_down ( :shift )
. send_keys ( 'a' )
. key_up ( :shift )
. send_keys ( 'b' )
. perform
expect ( driver . find_element ( id : 'textInput' ) . attribute ( 'value' )) . to eq 'Ab'
end
it 'sends keys to active element' do
driver . get 'https://www.selenium.dev/selenium/web/single_text_input.html'
wait . until { driver . find_element ( id : 'textInput' ) . attribute ( 'autofocus' ) }
driver . action
. send_keys ( 'abc' )
. perform
expect ( driver . find_element ( id : 'textInput' ) . attribute ( 'value' )) . to eq 'abc'
end
it 'sends keys to designated element' do
driver . get 'https://www.selenium.dev/selenium/web/single_text_input.html'
driver . find_element ( tag_name : 'body' ) . click
wait . until { driver . find_element ( id : 'textInput' ) . attribute ( 'autofocus' ) }
text_field = driver . find_element ( id : 'textInput' )
driver . action
. send_keys ( text_field , 'Selenium!' )
. perform
expect ( text_field . attribute ( 'value' )) . to eq 'Selenium!'
end
it 'copy and paste' do
driver . get 'https://www.selenium.dev/selenium/web/single_text_input.html'
wait . until { driver . find_element ( id : 'textInput' ) . attribute ( 'autofocus' ) }
cmd_ctrl = driver . capabilities . platform_name . include? ( 'mac' ) ? :command : :control
driver . action
. send_keys ( 'Selenium!' )
. send_keys ( :arrow_left )
. key_down ( :shift )
. send_keys ( :arrow_up )
. key_up ( :shift )
. key_down ( cmd_ctrl )
. send_keys ( 'xvv' )
. key_up ( cmd_ctrl )
. perform
expect ( driver . find_element ( id : 'textInput' ) . attribute ( 'value' )) . to eq 'SeleniumSelenium!'
end
end
await driver . actions ()
. sendKeys ( 'abc' )
. perform ()
Show full example const { By , Key , Browser , Builder } = require ( 'selenium-webdriver' )
const assert = require ( 'assert' )
const { platform } = require ( 'node:process' )
describe ( 'Keyboard Action - Keys test' , function () {
let driver
before ( async function () {
driver = await new Builder (). forBrowser ( 'chrome' ). build ();
})
after ( async () => await driver . quit ())
it ( 'KeyDown' , async function () {
await driver . get ( 'https://www.selenium.dev/selenium/web/single_text_input.html' )
await driver . actions ()
. keyDown ( Key . SHIFT )
. sendKeys ( 'a' )
. perform ()
const textField = driver . findElement ( By . id ( 'textInput' ))
assert . deepStrictEqual ( await textField . getAttribute ( 'value' ), 'A' )
})
it ( 'KeyUp' , async function () {
await driver . get ( 'https://www.selenium.dev/selenium/web/single_text_input.html' )
const textField = driver . findElement ( By . id ( 'textInput' ))
await textField . click ()
await driver . actions ()
. keyDown ( Key . SHIFT )
. sendKeys ( 'a' )
. keyUp ( Key . SHIFT )
. sendKeys ( 'b' )
. perform ()
assert . deepStrictEqual ( await textField . getAttribute ( 'value' ), 'Ab' )
})
it ( 'sendKeys' , async function () {
await driver . get ( 'https://www.selenium.dev/selenium/web/single_text_input.html' )
const textField = driver . findElement ( By . id ( 'textInput' ))
await textField . click ()
await driver . actions ()
. sendKeys ( 'abc' )
. perform ()
assert . deepStrictEqual ( await textField . getAttribute ( 'value' ), 'abc' )
})
it ( 'Designated Element' , async function () {
await driver . get ( 'https://www.selenium.dev/selenium/web/single_text_input.html' )
await driver . findElement ( By . css ( 'body' )). click ()
const textField = await driver . findElement ( By . id ( 'textInput' ))
await driver . actions ()
. sendKeys ( textField , 'abc' )
. perform ()
assert . deepStrictEqual ( await textField . getAttribute ( 'value' ), 'abc' )
})
it ( 'Copy and Paste' , async function () {
await driver . get ( 'https://www.selenium.dev/selenium/web/single_text_input.html' )
const textField = await driver . findElement ( By . id ( 'textInput' ))
const cmdCtrl = platform . includes ( 'darwin' ) ? Key . COMMAND : Key . CONTROL
await driver . actions ()
. click ( textField )
. sendKeys ( 'Selenium!' )
. sendKeys ( Key . ARROW_LEFT )
. keyDown ( Key . SHIFT )
. sendKeys ( Key . ARROW_UP )
. keyUp ( Key . SHIFT )
. keyDown ( cmdCtrl )
. sendKeys ( 'xvv' )
. keyUp ( cmdCtrl )
. perform ()
assert . deepStrictEqual ( await textField . getAttribute ( 'value' ), 'SeleniumSelenium!' )
})
})
Actions ( driver )
. sendKeys ( "abc" )
. perform ()
Show full example 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.HasCapabilities
import org.openqa.selenium.Keys
import org.openqa.selenium.Platform
import org.openqa.selenium.WebElement
import org.openqa.selenium.interactions.Actions
class KeysTest : BaseTest () {
@Test
fun keyDown () {
driver . get ( "https://www.selenium.dev/selenium/web/single_text_input.html" )
Actions ( driver )
. keyDown ( Keys . SHIFT )
. sendKeys ( "a" )
. perform ()
val textField = driver . findElement ( By . id ( "textInput" ))
Assertions . assertEquals ( "A" , textField . getAttribute ( "value" ))
}
@Test
fun keyUp () {
driver . get ( "https://www.selenium.dev/selenium/web/single_text_input.html" )
Actions ( driver )
. keyDown ( Keys . SHIFT )
. sendKeys ( "a" )
. keyUp ( Keys . SHIFT )
. sendKeys ( "b" )
. perform ()
val textField = driver . findElement ( By . id ( "textInput" ))
Assertions . assertEquals ( "Ab" , textField . getAttribute ( "value" ))
}
@Test
fun sendKeysToActiveElement () {
driver . get ( "https://www.selenium.dev/selenium/web/single_text_input.html" )
Actions ( driver )
. sendKeys ( "abc" )
. perform ()
val textField = driver . findElement ( By . id ( "textInput" ))
Assertions . assertEquals ( "abc" , textField . getAttribute ( "value" ))
}
@Test
fun sendKeysToDesignatedElement () {
driver . get ( "https://www.selenium.dev/selenium/web/single_text_input.html" )
driver . findElement ( By . tagName ( "body" )). click ()
val textField = driver . findElement ( By . id ( "textInput" ))
Actions ( driver )
. sendKeys ( textField , "Selenium!" )
. perform ()
Assertions . assertEquals ( "Selenium!" , textField . getAttribute ( "value" ))
}
@Test
fun copyAndPaste () {
driver . get ( "https://www.selenium.dev/selenium/web/single_text_input.html" )
val platformName = ( driver as HasCapabilities ). getCapabilities (). getPlatformName ()
val cmdCtrl = if ( platformName == Platform . MAC ) Keys . COMMAND else Keys . CONTROL
val textField = driver . findElement ( By . id ( "textInput" ))
Actions ( driver )
. sendKeys ( textField , "Selenium!" )
. sendKeys ( Keys . ARROW_LEFT )
. keyDown ( Keys . SHIFT )
. sendKeys ( Keys . ARROW_UP )
. keyUp ( Keys . SHIFT )
. keyDown ( cmdCtrl )
. sendKeys ( "xvv" )
. keyUp ( cmdCtrl )
. perform ()
Assertions . assertEquals ( "SeleniumSelenium!" , textField . getAttribute ( "value" ))
}
}
Elemento Designado
Java
Python
CSharp
Ruby
JavaScript
Kotlin new Actions ( driver )
. sendKeys ( textField , "Selenium!" )
. perform ();
Show full example 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.Platform ;
import org.openqa.selenium.WebElement ;
import org.openqa.selenium.interactions.Actions ;
public class KeysTest extends BaseChromeTest {
@Test
public void keyDown () {
driver . get ( "https://www.selenium.dev/selenium/web/single_text_input.html" );
new Actions ( driver )
. keyDown ( Keys . SHIFT )
. sendKeys ( "a" )
. perform ();
WebElement textField = driver . findElement ( By . id ( "textInput" ));
Assertions . assertEquals ( "A" , textField . getAttribute ( "value" ));
}
@Test
public void keyUp () {
driver . get ( "https://www.selenium.dev/selenium/web/single_text_input.html" );
new Actions ( driver )
. keyDown ( Keys . SHIFT )
. sendKeys ( "a" )
. keyUp ( Keys . SHIFT )
. sendKeys ( "b" )
. perform ();
WebElement textField = driver . findElement ( By . id ( "textInput" ));
Assertions . assertEquals ( "Ab" , textField . getAttribute ( "value" ));
}
@Test
public void sendKeysToActiveElement () {
driver . get ( "https://www.selenium.dev/selenium/web/single_text_input.html" );
new Actions ( driver )
. sendKeys ( "abc" )
. perform ();
WebElement textField = driver . findElement ( By . id ( "textInput" ));
Assertions . assertEquals ( "abc" , textField . getAttribute ( "value" ));
}
@Test
public void sendKeysToDesignatedElement () {
driver . get ( "https://www.selenium.dev/selenium/web/single_text_input.html" );
driver . findElement ( By . tagName ( "body" )). click ();
WebElement textField = driver . findElement ( By . id ( "textInput" ));
new Actions ( driver )
. sendKeys ( textField , "Selenium!" )
. perform ();
Assertions . assertEquals ( "Selenium!" , textField . getAttribute ( "value" ));
}
@Test
public void copyAndPaste () {
driver . get ( "https://www.selenium.dev/selenium/web/single_text_input.html" );
Keys cmdCtrl = Platform . getCurrent (). is ( Platform . MAC ) ? Keys . COMMAND : Keys . CONTROL ;
WebElement textField = driver . findElement ( By . id ( "textInput" ));
new Actions ( driver )
. sendKeys ( textField , "Selenium!" )
. sendKeys ( Keys . ARROW_LEFT )
. keyDown ( Keys . SHIFT )
. sendKeys ( Keys . ARROW_UP )
. keyUp ( Keys . SHIFT )
. keyDown ( cmdCtrl )
. sendKeys ( "xvv" )
. keyUp ( cmdCtrl )
. perform ();
Assertions . assertEquals ( "SeleniumSelenium!" , textField . getAttribute ( "value" ));
}
}
text_input = driver . find_element ( By . ID , "textInput" )
ActionChains ( driver ) \
. send_keys_to_element ( text_input , "abc" ) \
. perform ()
Show full example import sys
from selenium.webdriver import Keys , ActionChains
from selenium.webdriver.common.by import By
def test_key_down ( driver ):
driver . get ( 'https://selenium.dev/selenium/web/single_text_input.html' )
ActionChains ( driver ) \
. key_down ( Keys . SHIFT ) \
. send_keys ( "abc" ) \
. perform ()
assert driver . find_element ( By . ID , "textInput" ) . get_attribute ( 'value' ) == "ABC"
def test_key_up ( driver ):
driver . get ( 'https://selenium.dev/selenium/web/single_text_input.html' )
ActionChains ( driver ) \
. key_down ( Keys . SHIFT ) \
. send_keys ( "a" ) \
. key_up ( Keys . SHIFT ) \
. send_keys ( "b" ) \
. perform ()
assert driver . find_element ( By . ID , "textInput" ) . get_attribute ( 'value' ) == "Ab"
def test_send_keys_to_active_element ( driver ):
driver . get ( 'https://selenium.dev/selenium/web/single_text_input.html' )
ActionChains ( driver ) \
. send_keys ( "abc" ) \
. perform ()
assert driver . find_element ( By . ID , "textInput" ) . get_attribute ( 'value' ) == "abc"
def test_send_keys_to_designated_element ( driver ):
driver . get ( 'https://selenium.dev/selenium/web/single_text_input.html' )
driver . find_element ( By . TAG_NAME , "body" ) . click ()
text_input = driver . find_element ( By . ID , "textInput" )
ActionChains ( driver ) \
. send_keys_to_element ( text_input , "abc" ) \
. perform ()
assert driver . find_element ( By . ID , "textInput" ) . get_attribute ( 'value' ) == "abc"
def test_copy_and_paste ( firefox_driver ):
driver = firefox_driver
driver . get ( 'https://selenium.dev/selenium/web/single_text_input.html' )
cmd_ctrl = Keys . COMMAND if sys . platform == 'darwin' else Keys . CONTROL
ActionChains ( driver ) \
. send_keys ( "Selenium!" ) \
. send_keys ( Keys . ARROW_LEFT ) \
. key_down ( Keys . SHIFT ) \
. send_keys ( Keys . ARROW_UP ) \
. key_up ( Keys . SHIFT ) \
. key_down ( cmd_ctrl ) \
. send_keys ( "xvv" ) \
. key_up ( cmd_ctrl ) \
. perform ()
assert driver . find_element ( By . ID , "textInput" ) . get_attribute ( 'value' ) == "SeleniumSelenium!"
driver . FindElement ( By . TagName ( "body" )). Click ();
IWebElement textField = driver . FindElement ( By . Id ( "textInput" ));
new Actions ( driver )
Show full example using System ;
using Microsoft.VisualStudio.TestTools.UnitTesting ;
using OpenQA.Selenium ;
using OpenQA.Selenium.Interactions ;
namespace SeleniumDocs.ActionsAPI
{
[TestClass]
public class KeysTest : BaseFirefoxTest
{
[TestMethod]
public void KeyDown ()
{
driver . Url = "https://selenium.dev/selenium/web/single_text_input.html" ;
new Actions ( driver )
. KeyDown ( Keys . Shift )
. SendKeys ( "a" )
. Perform ();
IWebElement textField = driver . FindElement ( By . Id ( "textInput" ));
Assert . AreEqual ( "A" , textField . GetAttribute ( "value" ));
}
[TestMethod]
public void KeyUp ()
{
driver . Url = "https://selenium.dev/selenium/web/single_text_input.html" ;
new Actions ( driver )
. KeyDown ( Keys . Shift )
. SendKeys ( "a" )
. KeyUp ( Keys . Shift )
. SendKeys ( "b" )
. Perform ();
IWebElement textField = driver . FindElement ( By . Id ( "textInput" ));
Assert . AreEqual ( "Ab" , textField . GetAttribute ( "value" ));
}
[TestMethod]
public void SendKeysToActiveElement ()
{
driver . Url = "https://selenium.dev/selenium/web/single_text_input.html" ;
new Actions ( driver )
. SendKeys ( "abc" )
. Perform ();
IWebElement textField = driver . FindElement ( By . Id ( "textInput" ));
Assert . AreEqual ( "abc" , textField . GetAttribute ( "value" ));
}
[TestMethod]
public void SendKeysToDesignatedElement ()
{
driver . Url = "https://selenium.dev/selenium/web/single_text_input.html" ;
driver . FindElement ( By . TagName ( "body" )). Click ();
IWebElement textField = driver . FindElement ( By . Id ( "textInput" ));
new Actions ( driver )
. SendKeys ( textField , "abc" )
. Perform ();
Assert . AreEqual ( "abc" , textField . GetAttribute ( "value" ));
}
[TestMethod]
public void CopyAndPaste ()
{
driver . Url = "https://selenium.dev/selenium/web/single_text_input.html" ;
var capabilities = (( WebDriver ) driver ). Capabilities ;
String platformName = ( string ) capabilities . GetCapability ( "platformName" );
String cmdCtrl = platformName . Contains ( "mac" ) ? Keys . Command : Keys . Control ;
new Actions ( driver )
. SendKeys ( "Selenium!" )
. SendKeys ( Keys . ArrowLeft )
. KeyDown ( Keys . Shift )
. SendKeys ( Keys . ArrowUp )
. KeyUp ( Keys . Shift )
. KeyDown ( cmdCtrl )
. SendKeys ( "xvv" )
. KeyUp ( cmdCtrl )
. Perform ();
IWebElement textField = driver . FindElement ( By . Id ( "textInput" ));
Assert . AreEqual ( "SeleniumSelenium!" , textField . GetAttribute ( "value" ));
}
}
}
text_field = driver . find_element ( id : 'textInput' )
driver . action
. send_keys ( text_field , 'Selenium!' )
. perform
Show full example # frozen_string_literal: true
require 'spec_helper'
RSpec . describe 'Keys' do
let ( :driver ) { start_session }
let ( :wait ) { Selenium :: WebDriver :: Wait . new ( timeout : 2 ) }
it 'key down' do
driver . get 'https://www.selenium.dev/selenium/web/single_text_input.html'
wait . until { driver . find_element ( id : 'textInput' ) . attribute ( 'autofocus' ) }
driver . action
. key_down ( :shift )
. send_keys ( 'a' )
. perform
expect ( driver . find_element ( id : 'textInput' ) . attribute ( 'value' )) . to eq 'A'
end
it 'key up' do
driver . get 'https://www.selenium.dev/selenium/web/single_text_input.html'
wait . until { driver . find_element ( id : 'textInput' ) . attribute ( 'autofocus' ) }
driver . action
. key_down ( :shift )
. send_keys ( 'a' )
. key_up ( :shift )
. send_keys ( 'b' )
. perform
expect ( driver . find_element ( id : 'textInput' ) . attribute ( 'value' )) . to eq 'Ab'
end
it 'sends keys to active element' do
driver . get 'https://www.selenium.dev/selenium/web/single_text_input.html'
wait . until { driver . find_element ( id : 'textInput' ) . attribute ( 'autofocus' ) }
driver . action
. send_keys ( 'abc' )
. perform
expect ( driver . find_element ( id : 'textInput' ) . attribute ( 'value' )) . to eq 'abc'
end
it 'sends keys to designated element' do
driver . get 'https://www.selenium.dev/selenium/web/single_text_input.html'
driver . find_element ( tag_name : 'body' ) . click
wait . until { driver . find_element ( id : 'textInput' ) . attribute ( 'autofocus' ) }
text_field = driver . find_element ( id : 'textInput' )
driver . action
. send_keys ( text_field , 'Selenium!' )
. perform
expect ( text_field . attribute ( 'value' )) . to eq 'Selenium!'
end
it 'copy and paste' do
driver . get 'https://www.selenium.dev/selenium/web/single_text_input.html'
wait . until { driver . find_element ( id : 'textInput' ) . attribute ( 'autofocus' ) }
cmd_ctrl = driver . capabilities . platform_name . include? ( 'mac' ) ? :command : :control
driver . action
. send_keys ( 'Selenium!' )
. send_keys ( :arrow_left )
. key_down ( :shift )
. send_keys ( :arrow_up )
. key_up ( :shift )
. key_down ( cmd_ctrl )
. send_keys ( 'xvv' )
. key_up ( cmd_ctrl )
. perform
expect ( driver . find_element ( id : 'textInput' ) . attribute ( 'value' )) . to eq 'SeleniumSelenium!'
end
end
Selenium v4.5.0
const textField = await driver . findElement ( By . id ( 'textInput' ))
await driver . actions ()
. sendKeys ( textField , 'abc' )
. perform ()
Show full example const { By , Key , Browser , Builder } = require ( 'selenium-webdriver' )
const assert = require ( 'assert' )
const { platform } = require ( 'node:process' )
describe ( 'Keyboard Action - Keys test' , function () {
let driver
before ( async function () {
driver = await new Builder (). forBrowser ( 'chrome' ). build ();
})
after ( async () => await driver . quit ())
it ( 'KeyDown' , async function () {
await driver . get ( 'https://www.selenium.dev/selenium/web/single_text_input.html' )
await driver . actions ()
. keyDown ( Key . SHIFT )
. sendKeys ( 'a' )
. perform ()
const textField = driver . findElement ( By . id ( 'textInput' ))
assert . deepStrictEqual ( await textField . getAttribute ( 'value' ), 'A' )
})
it ( 'KeyUp' , async function () {
await driver . get ( 'https://www.selenium.dev/selenium/web/single_text_input.html' )
const textField = driver . findElement ( By . id ( 'textInput' ))
await textField . click ()
await driver . actions ()
. keyDown ( Key . SHIFT )
. sendKeys ( 'a' )
. keyUp ( Key . SHIFT )
. sendKeys ( 'b' )
. perform ()
assert . deepStrictEqual ( await textField . getAttribute ( 'value' ), 'Ab' )
})
it ( 'sendKeys' , async function () {
await driver . get ( 'https://www.selenium.dev/selenium/web/single_text_input.html' )
const textField = driver . findElement ( By . id ( 'textInput' ))
await textField . click ()
await driver . actions ()
. sendKeys ( 'abc' )
. perform ()
assert . deepStrictEqual ( await textField . getAttribute ( 'value' ), 'abc' )
})
it ( 'Designated Element' , async function () {
await driver . get ( 'https://www.selenium.dev/selenium/web/single_text_input.html' )
await driver . findElement ( By . css ( 'body' )). click ()
const textField = await driver . findElement ( By . id ( 'textInput' ))
await driver . actions ()
. sendKeys ( textField , 'abc' )
. perform ()
assert . deepStrictEqual ( await textField . getAttribute ( 'value' ), 'abc' )
})
it ( 'Copy and Paste' , async function () {
await driver . get ( 'https://www.selenium.dev/selenium/web/single_text_input.html' )
const textField = await driver . findElement ( By . id ( 'textInput' ))
const cmdCtrl = platform . includes ( 'darwin' ) ? Key . COMMAND : Key . CONTROL
await driver . actions ()
. click ( textField )
. sendKeys ( 'Selenium!' )
. sendKeys ( Key . ARROW_LEFT )
. keyDown ( Key . SHIFT )
. sendKeys ( Key . ARROW_UP )
. keyUp ( Key . SHIFT )
. keyDown ( cmdCtrl )
. sendKeys ( 'xvv' )
. keyUp ( cmdCtrl )
. perform ()
assert . deepStrictEqual ( await textField . getAttribute ( 'value' ), 'SeleniumSelenium!' )
})
})
val textField = driver . findElement ( By . id ( "textInput" ))
Actions ( driver )
. sendKeys ( textField , "Selenium!" )
. perform ()
Show full example 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.HasCapabilities
import org.openqa.selenium.Keys
import org.openqa.selenium.Platform
import org.openqa.selenium.WebElement
import org.openqa.selenium.interactions.Actions
class KeysTest : BaseTest () {
@Test
fun keyDown () {
driver . get ( "https://www.selenium.dev/selenium/web/single_text_input.html" )
Actions ( driver )
. keyDown ( Keys . SHIFT )
. sendKeys ( "a" )
. perform ()
val textField = driver . findElement ( By . id ( "textInput" ))
Assertions . assertEquals ( "A" , textField . getAttribute ( "value" ))
}
@Test
fun keyUp () {
driver . get ( "https://www.selenium.dev/selenium/web/single_text_input.html" )
Actions ( driver )
. keyDown ( Keys . SHIFT )
. sendKeys ( "a" )
. keyUp ( Keys . SHIFT )
. sendKeys ( "b" )
. perform ()
val textField = driver . findElement ( By . id ( "textInput" ))
Assertions . assertEquals ( "Ab" , textField . getAttribute ( "value" ))
}
@Test
fun sendKeysToActiveElement () {
driver . get ( "https://www.selenium.dev/selenium/web/single_text_input.html" )
Actions ( driver )
. sendKeys ( "abc" )
. perform ()
val textField = driver . findElement ( By . id ( "textInput" ))
Assertions . assertEquals ( "abc" , textField . getAttribute ( "value" ))
}
@Test
fun sendKeysToDesignatedElement () {
driver . get ( "https://www.selenium.dev/selenium/web/single_text_input.html" )
driver . findElement ( By . tagName ( "body" )). click ()
val textField = driver . findElement ( By . id ( "textInput" ))
Actions ( driver )
. sendKeys ( textField , "Selenium!" )
. perform ()
Assertions . assertEquals ( "Selenium!" , textField . getAttribute ( "value" ))
}
@Test
fun copyAndPaste () {
driver . get ( "https://www.selenium.dev/selenium/web/single_text_input.html" )
val platformName = ( driver as HasCapabilities ). getCapabilities (). getPlatformName ()
val cmdCtrl = if ( platformName == Platform . MAC ) Keys . COMMAND else Keys . CONTROL
val textField = driver . findElement ( By . id ( "textInput" ))
Actions ( driver )
. sendKeys ( textField , "Selenium!" )
. sendKeys ( Keys . ARROW_LEFT )
. keyDown ( Keys . SHIFT )
. sendKeys ( Keys . ARROW_UP )
. keyUp ( Keys . SHIFT )
. keyDown ( cmdCtrl )
. sendKeys ( "xvv" )
. keyUp ( cmdCtrl )
. perform ()
Assertions . assertEquals ( "SeleniumSelenium!" , textField . getAttribute ( "value" ))
}
}
Copiar e Colar Aqui está um exemplo de uso de todos os métodos acima para realizar uma ação de copiar/colar. Note que a tecla a ser usada para essa operação será diferente, dependendo se for um sistema Mac OS ou não. Este código resultará no texto: SeleniumSelenium!
Java
Python
CSharp
Ruby
JavaScript
Kotlin Keys cmdCtrl = Platform . getCurrent (). is ( Platform . MAC ) ? Keys . COMMAND : Keys . CONTROL ;
WebElement textField = driver . findElement ( By . id ( "textInput" ));
new Actions ( driver )
. sendKeys ( textField , "Selenium!" )
. sendKeys ( Keys . ARROW_LEFT )
. keyDown ( Keys . SHIFT )
. sendKeys ( Keys . ARROW_UP )
. keyUp ( Keys . SHIFT )
. keyDown ( cmdCtrl )
. sendKeys ( "xvv" )
. keyUp ( cmdCtrl )
. perform ();
Assertions . assertEquals ( "SeleniumSelenium!" , textField . getAttribute ( "value" ));
Show full example 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.Platform ;
import org.openqa.selenium.WebElement ;
import org.openqa.selenium.interactions.Actions ;
public class KeysTest extends BaseChromeTest {
@Test
public void keyDown () {
driver . get ( "https://www.selenium.dev/selenium/web/single_text_input.html" );
new Actions ( driver )
. keyDown ( Keys . SHIFT )
. sendKeys ( "a" )
. perform ();
WebElement textField = driver . findElement ( By . id ( "textInput" ));
Assertions . assertEquals ( "A" , textField . getAttribute ( "value" ));
}
@Test
public void keyUp () {
driver . get ( "https://www.selenium.dev/selenium/web/single_text_input.html" );
new Actions ( driver )
. keyDown ( Keys . SHIFT )
. sendKeys ( "a" )
. keyUp ( Keys . SHIFT )
. sendKeys ( "b" )
. perform ();
WebElement textField = driver . findElement ( By . id ( "textInput" ));
Assertions . assertEquals ( "Ab" , textField . getAttribute ( "value" ));
}
@Test
public void sendKeysToActiveElement () {
driver . get ( "https://www.selenium.dev/selenium/web/single_text_input.html" );
new Actions ( driver )
. sendKeys ( "abc" )
. perform ();
WebElement textField = driver . findElement ( By . id ( "textInput" ));
Assertions . assertEquals ( "abc" , textField . getAttribute ( "value" ));
}
@Test
public void sendKeysToDesignatedElement () {
driver . get ( "https://www.selenium.dev/selenium/web/single_text_input.html" );
driver . findElement ( By . tagName ( "body" )). click ();
WebElement textField = driver . findElement ( By . id ( "textInput" ));
new Actions ( driver )
. sendKeys ( textField , "Selenium!" )
. perform ();
Assertions . assertEquals ( "Selenium!" , textField . getAttribute ( "value" ));
}
@Test
public void copyAndPaste () {
driver . get ( "https://www.selenium.dev/selenium/web/single_text_input.html" );
Keys cmdCtrl = Platform . getCurrent (). is ( Platform . MAC ) ? Keys . COMMAND : Keys . CONTROL ;
WebElement textField = driver . findElement ( By . id ( "textInput" ));
new Actions ( driver )
. sendKeys ( textField , "Selenium!" )
. sendKeys ( Keys . ARROW_LEFT )
. keyDown ( Keys . SHIFT )
. sendKeys ( Keys . ARROW_UP )
. keyUp ( Keys . SHIFT )
. keyDown ( cmdCtrl )
. sendKeys ( "xvv" )
. keyUp ( cmdCtrl )
. perform ();
Assertions . assertEquals ( "SeleniumSelenium!" , textField . getAttribute ( "value" ));
}
}
cmd_ctrl = Keys . COMMAND if sys . platform == 'darwin' else Keys . CONTROL
ActionChains ( driver ) \
. send_keys ( "Selenium!" ) \
. send_keys ( Keys . ARROW_LEFT ) \
. key_down ( Keys . SHIFT ) \
. send_keys ( Keys . ARROW_UP ) \
. key_up ( Keys . SHIFT ) \
. key_down ( cmd_ctrl ) \
. send_keys ( "xvv" ) \
. key_up ( cmd_ctrl ) \
. perform ()
Show full example import sys
from selenium.webdriver import Keys , ActionChains
from selenium.webdriver.common.by import By
def test_key_down ( driver ):
driver . get ( 'https://selenium.dev/selenium/web/single_text_input.html' )
ActionChains ( driver ) \
. key_down ( Keys . SHIFT ) \
. send_keys ( "abc" ) \
. perform ()
assert driver . find_element ( By . ID , "textInput" ) . get_attribute ( 'value' ) == "ABC"
def test_key_up ( driver ):
driver . get ( 'https://selenium.dev/selenium/web/single_text_input.html' )
ActionChains ( driver ) \
. key_down ( Keys . SHIFT ) \
. send_keys ( "a" ) \
. key_up ( Keys . SHIFT ) \
. send_keys ( "b" ) \
. perform ()
assert driver . find_element ( By . ID , "textInput" ) . get_attribute ( 'value' ) == "Ab"
def test_send_keys_to_active_element ( driver ):
driver . get ( 'https://selenium.dev/selenium/web/single_text_input.html' )
ActionChains ( driver ) \
. send_keys ( "abc" ) \
. perform ()
assert driver . find_element ( By . ID , "textInput" ) . get_attribute ( 'value' ) == "abc"
def test_send_keys_to_designated_element ( driver ):
driver . get ( 'https://selenium.dev/selenium/web/single_text_input.html' )
driver . find_element ( By . TAG_NAME , "body" ) . click ()
text_input = driver . find_element ( By . ID , "textInput" )
ActionChains ( driver ) \
. send_keys_to_element ( text_input , "abc" ) \
. perform ()
assert driver . find_element ( By . ID , "textInput" ) . get_attribute ( 'value' ) == "abc"
def test_copy_and_paste ( firefox_driver ):
driver = firefox_driver
driver . get ( 'https://selenium.dev/selenium/web/single_text_input.html' )
cmd_ctrl = Keys . COMMAND if sys . platform == 'darwin' else Keys . CONTROL
ActionChains ( driver ) \
. send_keys ( "Selenium!" ) \
. send_keys ( Keys . ARROW_LEFT ) \
. key_down ( Keys . SHIFT ) \
. send_keys ( Keys . ARROW_UP ) \
. key_up ( Keys . SHIFT ) \
. key_down ( cmd_ctrl ) \
. send_keys ( "xvv" ) \
. key_up ( cmd_ctrl ) \
. perform ()
assert driver . find_element ( By . ID , "textInput" ) . get_attribute ( 'value' ) == "SeleniumSelenium!"
var capabilities = (( WebDriver ) driver ). Capabilities ;
String platformName = ( string ) capabilities . GetCapability ( "platformName" );
String cmdCtrl = platformName . Contains ( "mac" ) ? Keys . Command : Keys . Control ;
new Actions ( driver )
. SendKeys ( "Selenium!" )
. SendKeys ( Keys . ArrowLeft )
. KeyDown ( Keys . Shift )
. SendKeys ( Keys . ArrowUp )
Show full example using System ;
using Microsoft.VisualStudio.TestTools.UnitTesting ;
using OpenQA.Selenium ;
using OpenQA.Selenium.Interactions ;
namespace SeleniumDocs.ActionsAPI
{
[TestClass]
public class KeysTest : BaseFirefoxTest
{
[TestMethod]
public void KeyDown ()
{
driver . Url = "https://selenium.dev/selenium/web/single_text_input.html" ;
new Actions ( driver )
. KeyDown ( Keys . Shift )
. SendKeys ( "a" )
. Perform ();
IWebElement textField = driver . FindElement ( By . Id ( "textInput" ));
Assert . AreEqual ( "A" , textField . GetAttribute ( "value" ));
}
[TestMethod]
public void KeyUp ()
{
driver . Url = "https://selenium.dev/selenium/web/single_text_input.html" ;
new Actions ( driver )
. KeyDown ( Keys . Shift )
. SendKeys ( "a" )
. KeyUp ( Keys . Shift )
. SendKeys ( "b" )
. Perform ();
IWebElement textField = driver . FindElement ( By . Id ( "textInput" ));
Assert . AreEqual ( "Ab" , textField . GetAttribute ( "value" ));
}
[TestMethod]
public void SendKeysToActiveElement ()
{
driver . Url = "https://selenium.dev/selenium/web/single_text_input.html" ;
new Actions ( driver )
. SendKeys ( "abc" )
. Perform ();
IWebElement textField = driver . FindElement ( By . Id ( "textInput" ));
Assert . AreEqual ( "abc" , textField . GetAttribute ( "value" ));
}
[TestMethod]
public void SendKeysToDesignatedElement ()
{
driver . Url = "https://selenium.dev/selenium/web/single_text_input.html" ;
driver . FindElement ( By . TagName ( "body" )). Click ();
IWebElement textField = driver . FindElement ( By . Id ( "textInput" ));
new Actions ( driver )
. SendKeys ( textField , "abc" )
. Perform ();
Assert . AreEqual ( "abc" , textField . GetAttribute ( "value" ));
}
[TestMethod]
public void CopyAndPaste ()
{
driver . Url = "https://selenium.dev/selenium/web/single_text_input.html" ;
var capabilities = (( WebDriver ) driver ). Capabilities ;
String platformName = ( string ) capabilities . GetCapability ( "platformName" );
String cmdCtrl = platformName . Contains ( "mac" ) ? Keys . Command : Keys . Control ;
new Actions ( driver )
. SendKeys ( "Selenium!" )
. SendKeys ( Keys . ArrowLeft )
. KeyDown ( Keys . Shift )
. SendKeys ( Keys . ArrowUp )
. KeyUp ( Keys . Shift )
. KeyDown ( cmdCtrl )
. SendKeys ( "xvv" )
. KeyUp ( cmdCtrl )
. Perform ();
IWebElement textField = driver . FindElement ( By . Id ( "textInput" ));
Assert . AreEqual ( "SeleniumSelenium!" , textField . GetAttribute ( "value" ));
}
}
}
driver . action
. send_keys ( 'Selenium!' )
. send_keys ( :arrow_left )
. key_down ( :shift )
. send_keys ( :arrow_up )
. key_up ( :shift )
. key_down ( cmd_ctrl )
. send_keys ( 'xvv' )
. key_up ( cmd_ctrl )
. perform
Show full example # frozen_string_literal: true
require 'spec_helper'
RSpec . describe 'Keys' do
let ( :driver ) { start_session }
let ( :wait ) { Selenium :: WebDriver :: Wait . new ( timeout : 2 ) }
it 'key down' do
driver . get 'https://www.selenium.dev/selenium/web/single_text_input.html'
wait . until { driver . find_element ( id : 'textInput' ) . attribute ( 'autofocus' ) }
driver . action
. key_down ( :shift )
. send_keys ( 'a' )
. perform
expect ( driver . find_element ( id : 'textInput' ) . attribute ( 'value' )) . to eq 'A'
end
it 'key up' do
driver . get 'https://www.selenium.dev/selenium/web/single_text_input.html'
wait . until { driver . find_element ( id : 'textInput' ) . attribute ( 'autofocus' ) }
driver . action
. key_down ( :shift )
. send_keys ( 'a' )
. key_up ( :shift )
. send_keys ( 'b' )
. perform
expect ( driver . find_element ( id : 'textInput' ) . attribute ( 'value' )) . to eq 'Ab'
end
it 'sends keys to active element' do
driver . get 'https://www.selenium.dev/selenium/web/single_text_input.html'
wait . until { driver . find_element ( id : 'textInput' ) . attribute ( 'autofocus' ) }
driver . action
. send_keys ( 'abc' )
. perform
expect ( driver . find_element ( id : 'textInput' ) . attribute ( 'value' )) . to eq 'abc'
end
it 'sends keys to designated element' do
driver . get 'https://www.selenium.dev/selenium/web/single_text_input.html'
driver . find_element ( tag_name : 'body' ) . click
wait . until { driver . find_element ( id : 'textInput' ) . attribute ( 'autofocus' ) }
text_field = driver . find_element ( id : 'textInput' )
driver . action
. send_keys ( text_field , 'Selenium!' )
. perform
expect ( text_field . attribute ( 'value' )) . to eq 'Selenium!'
end
it 'copy and paste' do
driver . get 'https://www.selenium.dev/selenium/web/single_text_input.html'
wait . until { driver . find_element ( id : 'textInput' ) . attribute ( 'autofocus' ) }
cmd_ctrl = driver . capabilities . platform_name . include? ( 'mac' ) ? :command : :control
driver . action
. send_keys ( 'Selenium!' )
. send_keys ( :arrow_left )
. key_down ( :shift )
. send_keys ( :arrow_up )
. key_up ( :shift )
. key_down ( cmd_ctrl )
. send_keys ( 'xvv' )
. key_up ( cmd_ctrl )
. perform
expect ( driver . find_element ( id : 'textInput' ) . attribute ( 'value' )) . to eq 'SeleniumSelenium!'
end
end
const cmdCtrl = platform . includes ( 'darwin' ) ? Key . COMMAND : Key . CONTROL
await driver . actions ()
. click ( textField )
. sendKeys ( 'Selenium!' )
. sendKeys ( Key . ARROW_LEFT )
. keyDown ( Key . SHIFT )
. sendKeys ( Key . ARROW_UP )
. keyUp ( Key . SHIFT )
. keyDown ( cmdCtrl )
. sendKeys ( 'xvv' )
. keyUp ( cmdCtrl )
. perform ()
Show full example const { By , Key , Browser , Builder } = require ( 'selenium-webdriver' )
const assert = require ( 'assert' )
const { platform } = require ( 'node:process' )
describe ( 'Keyboard Action - Keys test' , function () {
let driver
before ( async function () {
driver = await new Builder (). forBrowser ( 'chrome' ). build ();
})
after ( async () => await driver . quit ())
it ( 'KeyDown' , async function () {
await driver . get ( 'https://www.selenium.dev/selenium/web/single_text_input.html' )
await driver . actions ()
. keyDown ( Key . SHIFT )
. sendKeys ( 'a' )
. perform ()
const textField = driver . findElement ( By . id ( 'textInput' ))
assert . deepStrictEqual ( await textField . getAttribute ( 'value' ), 'A' )
})
it ( 'KeyUp' , async function () {
await driver . get ( 'https://www.selenium.dev/selenium/web/single_text_input.html' )
const textField = driver . findElement ( By . id ( 'textInput' ))
await textField . click ()
await driver . actions ()
. keyDown ( Key . SHIFT )
. sendKeys ( 'a' )
. keyUp ( Key . SHIFT )
. sendKeys ( 'b' )
. perform ()
assert . deepStrictEqual ( await textField . getAttribute ( 'value' ), 'Ab' )
})
it ( 'sendKeys' , async function () {
await driver . get ( 'https://www.selenium.dev/selenium/web/single_text_input.html' )
const textField = driver . findElement ( By . id ( 'textInput' ))
await textField . click ()
await driver . actions ()
. sendKeys ( 'abc' )
. perform ()
assert . deepStrictEqual ( await textField . getAttribute ( 'value' ), 'abc' )
})
it ( 'Designated Element' , async function () {
await driver . get ( 'https://www.selenium.dev/selenium/web/single_text_input.html' )
await driver . findElement ( By . css ( 'body' )). click ()
const textField = await driver . findElement ( By . id ( 'textInput' ))
await driver . actions ()
. sendKeys ( textField , 'abc' )
. perform ()
assert . deepStrictEqual ( await textField . getAttribute ( 'value' ), 'abc' )
})
it ( 'Copy and Paste' , async function () {
await driver . get ( 'https://www.selenium.dev/selenium/web/single_text_input.html' )
const textField = await driver . findElement ( By . id ( 'textInput' ))
const cmdCtrl = platform . includes ( 'darwin' ) ? Key . COMMAND : Key . CONTROL
await driver . actions ()
. click ( textField )
. sendKeys ( 'Selenium!' )
. sendKeys ( Key . ARROW_LEFT )
. keyDown ( Key . SHIFT )
. sendKeys ( Key . ARROW_UP )
. keyUp ( Key . SHIFT )
. keyDown ( cmdCtrl )
. sendKeys ( 'xvv' )
. keyUp ( cmdCtrl )
. perform ()
assert . deepStrictEqual ( await textField . getAttribute ( 'value' ), 'SeleniumSelenium!' )
})
})
val cmdCtrl = if ( platformName == Platform . MAC ) Keys . COMMAND else Keys . CONTROL
val textField = driver . findElement ( By . id ( "textInput" ))
Actions ( driver )
. sendKeys ( textField , "Selenium!" )
. sendKeys ( Keys . ARROW_LEFT )
. keyDown ( Keys . SHIFT )
. sendKeys ( Keys . ARROW_UP )
. keyUp ( Keys . SHIFT )
. keyDown ( cmdCtrl )
. sendKeys ( "xvv" )
. keyUp ( cmdCtrl )
. perform ()
Show full example 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.HasCapabilities
import org.openqa.selenium.Keys
import org.openqa.selenium.Platform
import org.openqa.selenium.WebElement
import org.openqa.selenium.interactions.Actions
class KeysTest : BaseTest () {
@Test
fun keyDown () {
driver . get ( "https://www.selenium.dev/selenium/web/single_text_input.html" )
Actions ( driver )
. keyDown ( Keys . SHIFT )
. sendKeys ( "a" )
. perform ()
val textField = driver . findElement ( By . id ( "textInput" ))
Assertions . assertEquals ( "A" , textField . getAttribute ( "value" ))
}
@Test
fun keyUp () {
driver . get ( "https://www.selenium.dev/selenium/web/single_text_input.html" )
Actions ( driver )
. keyDown ( Keys . SHIFT )
. sendKeys ( "a" )
. keyUp ( Keys . SHIFT )
. sendKeys ( "b" )
. perform ()
val textField = driver . findElement ( By . id ( "textInput" ))
Assertions . assertEquals ( "Ab" , textField . getAttribute ( "value" ))
}
@Test
fun sendKeysToActiveElement () {
driver . get ( "https://www.selenium.dev/selenium/web/single_text_input.html" )
Actions ( driver )
. sendKeys ( "abc" )
. perform ()
val textField = driver . findElement ( By . id ( "textInput" ))
Assertions . assertEquals ( "abc" , textField . getAttribute ( "value" ))
}
@Test
fun sendKeysToDesignatedElement () {
driver . get ( "https://www.selenium.dev/selenium/web/single_text_input.html" )
driver . findElement ( By . tagName ( "body" )). click ()
val textField = driver . findElement ( By . id ( "textInput" ))
Actions ( driver )
. sendKeys ( textField , "Selenium!" )
. perform ()
Assertions . assertEquals ( "Selenium!" , textField . getAttribute ( "value" ))
}
@Test
fun copyAndPaste () {
driver . get ( "https://www.selenium.dev/selenium/web/single_text_input.html" )
val platformName = ( driver as HasCapabilities ). getCapabilities (). getPlatformName ()
val cmdCtrl = if ( platformName == Platform . MAC ) Keys . COMMAND else Keys . CONTROL
val textField = driver . findElement ( By . id ( "textInput" ))
Actions ( driver )
. sendKeys ( textField , "Selenium!" )
. sendKeys ( Keys . ARROW_LEFT )
. keyDown ( Keys . SHIFT )
. sendKeys ( Keys . ARROW_UP )
. keyUp ( Keys . SHIFT )
. keyDown ( cmdCtrl )
. sendKeys ( "xvv" )
. keyUp ( cmdCtrl )
. perform ()
Assertions . assertEquals ( "SeleniumSelenium!" , textField . getAttribute ( "value" ))
}
}
2 - Ações do Mouse Uma representação de qualquer dispositivo de ponteiro para interagir com uma página da web.
Existem apenas 3 ações que podem ser realizadas com um mouse: pressionar um botão, liberar um botão pressionado e mover o mouse. O Selenium fornece métodos de conveniência que combinam essas ações da maneira mais comum.
Clicar e Manter Pressionado Este método combina mover o mouse para o centro de um elemento com a pressão do botão esquerdo do mouse. Isso é útil para focar em um elemento específico:
Java
Python
CSharp
Ruby
JavaScript
Kotlin WebElement clickable = driver . findElement ( By . id ( "clickable" ));
new Actions ( driver )
. clickAndHold ( clickable )
. perform ();
Show full example 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.Rectangle ;
import org.openqa.selenium.WebElement ;
import org.openqa.selenium.interactions.Actions ;
import org.openqa.selenium.interactions.PointerInput ;
import org.openqa.selenium.interactions.Sequence ;
import org.openqa.selenium.remote.RemoteWebDriver ;
import java.time.Duration ;
import java.util.Collections ;
public class MouseTest extends BaseChromeTest {
@Test
public void clickAndHold () {
driver . get ( "https://www.selenium.dev/selenium/web/mouse_interaction.html" );
WebElement clickable = driver . findElement ( By . id ( "clickable" ));
new Actions ( driver )
. clickAndHold ( clickable )
. perform ();
Assertions . assertEquals ( "focused" , driver . findElement ( By . id ( "click-status" )). getText ());
}
@Test
public void clickAndRelease () {
driver . get ( "https://www.selenium.dev/selenium/web/mouse_interaction.html" );
WebElement clickable = driver . findElement ( By . id ( "click" ));
new Actions ( driver )
. click ( clickable )
. perform ();
Assertions . assertTrue ( driver . getCurrentUrl (). contains ( "resultPage.html" ));
}
@Test
public void rightClick () {
driver . get ( "https://www.selenium.dev/selenium/web/mouse_interaction.html" );
WebElement clickable = driver . findElement ( By . id ( "clickable" ));
new Actions ( driver )
. contextClick ( clickable )
. perform ();
Assertions . assertEquals ( "context-clicked" , driver . findElement ( By . id ( "click-status" )). getText ());
}
@Test
public void backClick () {
driver . get ( "https://www.selenium.dev/selenium/web/mouse_interaction.html" );
driver . findElement ( By . id ( "click" )). click ();
Assertions . assertEquals ( driver . getTitle (), "We Arrive Here" );
PointerInput mouse = new PointerInput ( PointerInput . Kind . MOUSE , "default mouse" );
Sequence actions = new Sequence ( mouse , 0 )
. addAction ( mouse . createPointerDown ( PointerInput . MouseButton . BACK . asArg ()))
. addAction ( mouse . createPointerUp ( PointerInput . MouseButton . BACK . asArg ()));
(( RemoteWebDriver ) driver ). perform ( Collections . singletonList ( actions ));
Assertions . assertEquals ( "BasicMouseInterfaceTest" , driver . getTitle ());
}
@Test
public void forwardClick () {
driver . get ( "https://www.selenium.dev/selenium/web/mouse_interaction.html" );
driver . findElement ( By . id ( "click" )). click ();
driver . navigate (). back ();
Assertions . assertEquals ( driver . getTitle (), "BasicMouseInterfaceTest" );
PointerInput mouse = new PointerInput ( PointerInput . Kind . MOUSE , "default mouse" );
Sequence actions = new Sequence ( mouse , 0 )
. addAction ( mouse . createPointerDown ( PointerInput . MouseButton . FORWARD . asArg ()))
. addAction ( mouse . createPointerUp ( PointerInput . MouseButton . FORWARD . asArg ()));
(( RemoteWebDriver ) driver ). perform ( Collections . singletonList ( actions ));
Assertions . assertEquals ( "We Arrive Here" , driver . getTitle ());
}
@Test
public void doubleClick () {
driver . get ( "https://www.selenium.dev/selenium/web/mouse_interaction.html" );
WebElement clickable = driver . findElement ( By . id ( "clickable" ));
new Actions ( driver )
. doubleClick ( clickable )
. perform ();
Assertions . assertEquals ( "double-clicked" , driver . findElement ( By . id ( "click-status" )). getText ());
}
@Test
public void hovers () {
driver . get ( "https://www.selenium.dev/selenium/web/mouse_interaction.html" );
WebElement hoverable = driver . findElement ( By . id ( "hover" ));
new Actions ( driver )
. moveToElement ( hoverable )
. perform ();
Assertions . assertEquals ( "hovered" , driver . findElement ( By . id ( "move-status" )). getText ());
}
@Test
public void moveByOffsetFromElement () {
driver . get ( "https://www.selenium.dev/selenium/web/mouse_interaction.html" );
driver . manage (). window (). fullscreen ();
WebElement tracker = driver . findElement ( By . id ( "mouse-tracker" ));
new Actions ( driver )
. moveToElement ( tracker , 8 , 0 )
. perform ();
String [] result = driver . findElement ( By . id ( "relative-location" )). getText (). split ( ", " );
Assertions . assertTrue ( Math . abs ( Integer . parseInt ( result [ 0 ] ) - 100 - 8 ) < 2 );
}
@Test
public void moveByOffsetFromViewport () {
driver . get ( "https://www.selenium.dev/selenium/web/mouse_interaction.html" );
PointerInput mouse = new PointerInput ( PointerInput . Kind . MOUSE , "default mouse" );
Sequence actions = new Sequence ( mouse , 0 )
. addAction ( mouse . createPointerMove ( Duration . ZERO , PointerInput . Origin . viewport (), 8 , 12 ));
(( RemoteWebDriver ) driver ). perform ( Collections . singletonList ( actions ));
String [] result = driver . findElement ( By . id ( "absolute-location" )). getText (). split ( ", " );
Assertions . assertTrue ( Math . abs ( Integer . parseInt ( result [ 0 ] ) - 8 ) < 2 );
Assertions . assertTrue ( Math . abs ( Integer . parseInt ( result [ 1 ] ) - 12 ) < 2 );
}
@Test
public void moveByOffsetFromCurrentPointer () {
driver . get ( "https://www.selenium.dev/selenium/web/mouse_interaction.html" );
PointerInput mouse = new PointerInput ( PointerInput . Kind . MOUSE , "default mouse" );
Sequence actions = new Sequence ( mouse , 0 )
. addAction ( mouse . createPointerMove ( Duration . ZERO , PointerInput . Origin . viewport (), 8 , 11 ));
(( RemoteWebDriver ) driver ). perform ( Collections . singletonList ( actions ));
new Actions ( driver )
. moveByOffset ( 13 , 15 )
. perform ();
String [] result = driver . findElement ( By . id ( "absolute-location" )). getText (). split ( ", " );
Assertions . assertTrue ( Math . abs ( Integer . parseInt ( result [ 0 ] ) - 8 - 13 ) < 2 );
Assertions . assertTrue ( Math . abs ( Integer . parseInt ( result [ 1 ] ) - 11 - 15 ) < 2 );
}
@Test
public void dragsToElement () {
driver . get ( "https://www.selenium.dev/selenium/web/mouse_interaction.html" );
WebElement draggable = driver . findElement ( By . id ( "draggable" ));
WebElement droppable = driver . findElement ( By . id ( "droppable" ));
new Actions ( driver )
. dragAndDrop ( draggable , droppable )
. perform ();
Assertions . assertEquals ( "dropped" , driver . findElement ( By . id ( "drop-status" )). getText ());
}
@Test
public void dragsByOffset () {
driver . get ( "https://www.selenium.dev/selenium/web/mouse_interaction.html" );
WebElement draggable = driver . findElement ( By . id ( "draggable" ));
Rectangle start = draggable . getRect ();
Rectangle finish = driver . findElement ( By . id ( "droppable" )). getRect ();
new Actions ( driver )
. dragAndDropBy ( draggable , finish . getX () - start . getX (), finish . getY () - start . getY ())
. perform ();
Assertions . assertEquals ( "dropped" , driver . findElement ( By . id ( "drop-status" )). getText ());
}
}
clickable = driver . find_element ( By . ID , "clickable" )
ActionChains ( driver ) \
. click_and_hold ( clickable ) \
. perform ()
Show full example import pytest
from time import sleep
from selenium.webdriver import ActionChains
from selenium.webdriver.common.actions.action_builder import ActionBuilder
from selenium.webdriver.common.actions.mouse_button import MouseButton
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
def test_click_and_hold ( driver ):
driver . get ( 'https://selenium.dev/selenium/web/mouse_interaction.html' )
clickable = driver . find_element ( By . ID , "clickable" )
ActionChains ( driver ) \
. click_and_hold ( clickable ) \
. perform ()
sleep ( 0.5 )
assert driver . find_element ( By . ID , "click-status" ) . text == "focused"
def test_click_and_release ( driver ):
driver . get ( 'https://selenium.dev/selenium/web/mouse_interaction.html' )
clickable = driver . find_element ( By . ID , "click" )
ActionChains ( driver ) \
. click ( clickable ) \
. perform ()
assert "resultPage.html" in driver . current_url
def test_right_click ( driver ):
driver . get ( 'https://selenium.dev/selenium/web/mouse_interaction.html' )
clickable = driver . find_element ( By . ID , "clickable" )
ActionChains ( driver ) \
. context_click ( clickable ) \
. perform ()
sleep ( 0.5 )
assert driver . find_element ( By . ID , "click-status" ) . text == "context-clicked"
def test_back_click_ab ( driver ):
driver . get ( 'https://selenium.dev/selenium/web/mouse_interaction.html' )
driver . find_element ( By . ID , "click" ) . click ()
assert driver . title == "We Arrive Here"
action = ActionBuilder ( driver )
action . pointer_action . pointer_down ( MouseButton . BACK )
action . pointer_action . pointer_up ( MouseButton . BACK )
action . perform ()
assert driver . title == "BasicMouseInterfaceTest"
def test_forward_click_ab ( driver ):
driver . get ( 'https://selenium.dev/selenium/web/mouse_interaction.html' )
driver . find_element ( By . ID , "click" ) . click ()
driver . back ()
assert driver . title == "BasicMouseInterfaceTest"
action = ActionBuilder ( driver )
action . pointer_action . pointer_down ( MouseButton . FORWARD )
action . pointer_action . pointer_up ( MouseButton . FORWARD )
action . perform ()
assert driver . title == "We Arrive Here"
def test_double_click ( driver ):
driver . get ( 'https://selenium.dev/selenium/web/mouse_interaction.html' )
clickable = driver . find_element ( By . ID , "clickable" )
ActionChains ( driver ) \
. double_click ( clickable ) \
. perform ()
assert driver . find_element ( By . ID , "click-status" ) . text == "double-clicked"
def test_hover ( driver ):
driver . get ( 'https://selenium.dev/selenium/web/mouse_interaction.html' )
hoverable = driver . find_element ( By . ID , "hover" )
ActionChains ( driver ) \
. move_to_element ( hoverable ) \
. perform ()
assert driver . find_element ( By . ID , "move-status" ) . text == "hovered"
def test_move_by_offset_from_element ( driver ):
driver . get ( 'https://selenium.dev/selenium/web/mouse_interaction.html' )
mouse_tracker = driver . find_element ( By . ID , "mouse-tracker" )
ActionChains ( driver ) \
. move_to_element_with_offset ( mouse_tracker , 8 , 0 ) \
. perform ()
coordinates = driver . find_element ( By . ID , "relative-location" ) . text . split ( ", " )
assert abs ( int ( coordinates [ 0 ]) - 100 - 8 ) < 2
def test_move_by_offset_from_viewport_origin_ab ( driver ):
driver . get ( 'https://selenium.dev/selenium/web/mouse_interaction.html' )
WebDriverWait ( driver , 10 ) . until ( EC . presence_of_element_located (( By . ID , "absolute-location" )))
action = ActionBuilder ( driver )
action . pointer_action . move_to_location ( 8 , 0 )
action . perform ()
coordinates = driver . find_element ( By . ID , "absolute-location" ) . text . split ( ", " )
assert abs ( int ( coordinates [ 0 ]) - 8 ) < 2
def test_move_by_offset_from_current_pointer_ab ( driver ):
driver . get ( 'https://selenium.dev/selenium/web/mouse_interaction.html' )
action = ActionBuilder ( driver )
action . pointer_action . move_to_location ( 6 , 3 )
action . perform ()
ActionChains ( driver ) \
. move_by_offset ( 13 , 15 ) \
. perform ()
coordinates = driver . find_element ( By . ID , "absolute-location" ) . text . split ( ", " )
assert abs ( int ( coordinates [ 0 ]) - 6 - 13 ) < 2
assert abs ( int ( coordinates [ 1 ]) - 3 - 15 ) < 2
def test_drag_and_drop_onto_element ( driver ):
driver . get ( 'https://selenium.dev/selenium/web/mouse_interaction.html' )
draggable = driver . find_element ( By . ID , "draggable" )
droppable = driver . find_element ( By . ID , "droppable" )
ActionChains ( driver ) \
. drag_and_drop ( draggable , droppable ) \
. perform ()
assert driver . find_element ( By . ID , "drop-status" ) . text == "dropped"
def test_drag_and_drop_by_offset ( driver ):
driver . get ( 'https://selenium.dev/selenium/web/mouse_interaction.html' )
draggable = driver . find_element ( By . ID , "draggable" )
start = draggable . location
finish = driver . find_element ( By . ID , "droppable" ) . location
ActionChains ( driver ) \
. drag_and_drop_by_offset ( draggable , finish [ 'x' ] - start [ 'x' ], finish [ 'y' ] - start [ 'y' ]) \
. perform ()
assert driver . find_element ( By . ID , "drop-status" ) . text == "dropped"
IWebElement clickable = driver . FindElement ( By . Id ( "clickable" ));
new Actions ( driver )
. ClickAndHold ( clickable )
. Perform ();
Show full example using System ;
using System.Drawing ;
using Microsoft.VisualStudio.TestTools.UnitTesting ;
using OpenQA.Selenium ;
using OpenQA.Selenium.Interactions ;
namespace SeleniumDocs.ActionsAPI
{
[TestClass]
public class MouseTest : BaseChromeTest
{
[TestMethod]
public void ClickAndHold ()
{
driver . Url = "https://selenium.dev/selenium/web/mouse_interaction.html" ;
IWebElement clickable = driver . FindElement ( By . Id ( "clickable" ));
new Actions ( driver )
. ClickAndHold ( clickable )
. Perform ();
Assert . AreEqual ( "focused" , driver . FindElement ( By . Id ( "click-status" )). Text );
}
[TestMethod]
public void ClickAndRelease ()
{
driver . Url = "https://selenium.dev/selenium/web/mouse_interaction.html" ;
IWebElement clickable = driver . FindElement ( By . Id ( "click" ));
new Actions ( driver )
. Click ( clickable )
. Perform ();
Assert . IsTrue ( driver . Url . Contains ( "resultPage.html" ));
}
[TestMethod]
public void RightClick ()
{
driver . Url = "https://selenium.dev/selenium/web/mouse_interaction.html" ;
IWebElement clickable = driver . FindElement ( By . Id ( "clickable" ));
new Actions ( driver )
. ContextClick ( clickable )
. Perform ();
Assert . AreEqual ( "context-clicked" , driver . FindElement ( By . Id ( "click-status" )). Text );
}
[TestMethod]
public void BackClick ()
{
driver . Url = "https://selenium.dev/selenium/web/mouse_interaction.html" ;
driver . FindElement ( By . Id ( "click" )). Click ();
Assert . AreEqual ( "We Arrive Here" , driver . Title );
ActionBuilder actionBuilder = new ActionBuilder ();
PointerInputDevice mouse = new PointerInputDevice ( PointerKind . Mouse , "default mouse" );
actionBuilder . AddAction ( mouse . CreatePointerDown ( MouseButton . Back ));
actionBuilder . AddAction ( mouse . CreatePointerUp ( MouseButton . Back ));
(( IActionExecutor ) driver ). PerformActions ( actionBuilder . ToActionSequenceList ());
Assert . AreEqual ( "BasicMouseInterfaceTest" , driver . Title );
}
[TestMethod]
public void ForwardClick ()
{
driver . Url = "https://selenium.dev/selenium/web/mouse_interaction.html" ;
driver . FindElement ( By . Id ( "click" )). Click ();
driver . Navigate (). Back ();
Assert . AreEqual ( "BasicMouseInterfaceTest" , driver . Title );
ActionBuilder actionBuilder = new ActionBuilder ();
PointerInputDevice mouse = new PointerInputDevice ( PointerKind . Mouse , "default mouse" );
actionBuilder . AddAction ( mouse . CreatePointerDown ( MouseButton . Forward ));
actionBuilder . AddAction ( mouse . CreatePointerUp ( MouseButton . Forward ));
(( IActionExecutor ) driver ). PerformActions ( actionBuilder . ToActionSequenceList ());
Assert . AreEqual ( "We Arrive Here" , driver . Title );
}
[TestMethod]
public void DoubleClick ()
{
driver . Url = "https://selenium.dev/selenium/web/mouse_interaction.html" ;
IWebElement clickable = driver . FindElement ( By . Id ( "clickable" ));
new Actions ( driver )
. DoubleClick ( clickable )
. Perform ();
Assert . AreEqual ( "double-clicked" , driver . FindElement ( By . Id ( "click-status" )). Text );
}
[TestMethod]
public void Hovers ()
{
driver . Url = "https://selenium.dev/selenium/web/mouse_interaction.html" ;
IWebElement hoverable = driver . FindElement ( By . Id ( "hover" ));
new Actions ( driver )
. MoveToElement ( hoverable )
. Perform ();
Assert . AreEqual ( "hovered" , driver . FindElement ( By . Id ( "move-status" )). Text );
}
[TestMethod]
[Obsolete("Obsolete")]
public void MoveByOffsetFromTopLeftOfElement ()
{
driver . Url = "https://selenium.dev/selenium/web/mouse_interaction.html" ;
IWebElement tracker = driver . FindElement ( By . Id ( "mouse-tracker" ));
new Actions ( driver )
. MoveToElement ( tracker , 8 , 0 )
. Perform ();
string [] result = driver . FindElement ( By . Id ( "relative-location" )). Text . Split ( ", " );
Assert . IsTrue ( Math . Abs ( int . Parse ( result [ 0 ]) - 100 - 8 ) < 2 );
}
[TestMethod]
public void MoveByOffsetFromCenterOfElement ()
{
driver . Url = "https://selenium.dev/selenium/web/mouse_interaction.html" ;
IWebElement tracker = driver . FindElement ( By . Id ( "mouse-tracker" ));
new Actions ( driver )
. MoveToElement ( tracker , 8 , 0 )
. Perform ();
string [] result = driver . FindElement ( By . Id ( "relative-location" )). Text . Split ( ", " );
Assert . IsTrue ( Math . Abs ( int . Parse ( result [ 0 ]) - 100 - 8 ) < 2 );
}
[TestMethod]
public void MoveByOffsetFromViewport ()
{
driver . Url = "https://selenium.dev/selenium/web/mouse_interaction.html" ;
ActionBuilder actionBuilder = new ActionBuilder ();
PointerInputDevice mouse = new PointerInputDevice ( PointerKind . Mouse , "default mouse" );
actionBuilder . AddAction ( mouse . CreatePointerMove ( CoordinateOrigin . Viewport ,
8 , 0 , TimeSpan . Zero ));
(( IActionExecutor ) driver ). PerformActions ( actionBuilder . ToActionSequenceList ());
string [] result = driver . FindElement ( By . Id ( "absolute-location" )). Text . Split ( ", " );
Assert . IsTrue ( Math . Abs ( int . Parse ( result [ 0 ]) - 8 ) < 2 );
}
[TestMethod]
public void MoveByOffsetFromCurrentPointerLocation ()
{
driver . Url = "https://selenium.dev/selenium/web/mouse_interaction.html" ;
ActionBuilder actionBuilder = new ActionBuilder ();
PointerInputDevice mouse = new PointerInputDevice ( PointerKind . Mouse , "default mouse" );
actionBuilder . AddAction ( mouse . CreatePointerMove ( CoordinateOrigin . Viewport ,
8 , 12 , TimeSpan . Zero ));
(( IActionExecutor ) driver ). PerformActions ( actionBuilder . ToActionSequenceList ());
new Actions ( driver )
. MoveByOffset ( 13 , 15 )
. Perform ();
string [] result = driver . FindElement ( By . Id ( "absolute-location" )). Text . Split ( ", " );
Assert . IsTrue ( Math . Abs ( int . Parse ( result [ 0 ]) - 8 - 13 ) < 2 );
Assert . IsTrue ( Math . Abs ( int . Parse ( result [ 1 ]) - 12 - 15 ) < 2 );
}
[TestMethod]
public void DragToElement ()
{
driver . Url = "https://selenium.dev/selenium/web/mouse_interaction.html" ;
IWebElement draggable = driver . FindElement ( By . Id ( "draggable" ));
IWebElement droppable = driver . FindElement ( By . Id ( "droppable" ));
new Actions ( driver )
. DragAndDrop ( draggable , droppable )
. Perform ();
Assert . AreEqual ( "dropped" , driver . FindElement ( By . Id ( "drop-status" )). Text );
}
[TestMethod]
public void DragByOffset ()
{
driver . Url = "https://selenium.dev/selenium/web/mouse_interaction.html" ;
IWebElement draggable = driver . FindElement ( By . Id ( "draggable" ));
Point start = draggable . Location ;
Point finish = driver . FindElement ( By . Id ( "droppable" )). Location ;
new Actions ( driver )
. DragAndDropToOffset ( draggable , finish . X - start . X , finish . Y - start . Y )
. Perform ();
Assert . AreEqual ( "dropped" , driver . FindElement ( By . Id ( "drop-status" )). Text );
}
}
}
clickable = driver . find_element ( id : 'clickable' )
driver . action
. click_and_hold ( clickable )
. perform
Show full example # frozen_string_literal: true
require 'spec_helper'
RSpec . describe 'Mouse' do
let ( :driver ) { start_session }
it 'click and hold' do
driver . get 'https://www.selenium.dev/selenium/web/mouse_interaction.html'
clickable = driver . find_element ( id : 'clickable' )
driver . action
. click_and_hold ( clickable )
. perform
expect ( driver . find_element ( id : 'click-status' ) . text ) . to eq 'focused'
end
it 'click and release' do
driver . get 'https://www.selenium.dev/selenium/web/mouse_interaction.html'
clickable = driver . find_element ( id : 'click' )
driver . action
. click ( clickable )
. perform
expect ( driver . current_url ) . to include 'resultPage.html'
end
describe 'alternate button clicks' do
it 'right click' do
driver . get 'https://www.selenium.dev/selenium/web/mouse_interaction.html'
clickable = driver . find_element ( id : 'clickable' )
driver . action
. context_click ( clickable )
. perform
expect ( driver . find_element ( id : 'click-status' ) . text ) . to eq 'context-clicked'
end
it 'back click' do
driver . get 'https://www.selenium.dev/selenium/web/mouse_interaction.html'
driver . find_element ( id : 'click' ) . click
expect ( driver . title ) . to eq ( 'We Arrive Here' )
driver . action
. pointer_down ( :back )
. pointer_up ( :back )
. perform
expect ( driver . title ) . to eq ( 'BasicMouseInterfaceTest' )
end
it 'forward click' do
driver . get 'https://www.selenium.dev/selenium/web/mouse_interaction.html'
driver . find_element ( id : 'click' ) . click
driver . navigate . back
expect ( driver . title ) . to eq ( 'BasicMouseInterfaceTest' )
driver . action
. pointer_down ( :forward )
. pointer_up ( :forward )
. perform
expect ( driver . title ) . to eq ( 'We Arrive Here' )
end
end
it 'double click' do
driver . get 'https://www.selenium.dev/selenium/web/mouse_interaction.html'
clickable = driver . find_element ( id : 'clickable' )
driver . action
. double_click ( clickable )
. perform
expect ( driver . find_element ( id : 'click-status' ) . text ) . to eq 'double-clicked'
end
it 'hovers' do
driver . get 'https://www.selenium.dev/selenium/web/mouse_interaction.html'
hoverable = driver . find_element ( id : 'hover' )
driver . action
. move_to ( hoverable )
. perform
expect ( driver . find_element ( id : 'move-status' ) . text ) . to eq 'hovered'
end
describe 'move by offset' do
it 'offset from element' do
driver . get 'https://www.selenium.dev/selenium/web/mouse_interaction.html'
driver . action . scroll_to ( driver . find_element ( id : 'bottom' )) . perform
mouse_tracker = driver . find_element ( id : 'mouse-tracker' )
driver . action
. move_to ( mouse_tracker , 8 , 11 )
. perform
rect = mouse_tracker . rect
center_x = rect . width / 2
center_y = rect . height / 2
x_coord , y_coord = driver . find_element ( id : 'relative-location' ) . text . split ( ',' ) . map ( & :to_i )
expect ( x_coord ) . to be_within ( 1 ) . of ( center_x + 8 )
expect ( y_coord ) . to be_within ( 1 ) . of ( center_y + 11 )
end
it 'offset from viewport' do
driver . get 'https://www.selenium.dev/selenium/web/mouse_interaction.html'
driver . action
. move_to_location ( 8 , 12 )
. perform
x_coord , y_coord = driver . find_element ( id : 'absolute-location' ) . text . split ( ',' ) . map ( & :to_i )
expect ( x_coord ) . to be_within ( 1 ) . of ( 8 )
expect ( y_coord ) . to be_within ( 1 ) . of ( 12 )
end
it 'offset from current pointer location' do
driver . get 'https://www.selenium.dev/selenium/web/mouse_interaction.html'
driver . action . move_to_location ( 8 , 11 ) . perform
driver . action
. move_by ( 13 , 15 )
. perform
x_coord , y_coord = driver . find_element ( id : 'absolute-location' ) . text . split ( ',' ) . map ( & :to_i )
expect ( x_coord ) . to be_within ( 1 ) . of ( 8 + 13 )
expect ( y_coord ) . to be_within ( 1 ) . of ( 11 + 15 )
end
end
it 'drags to another element' do
driver . get 'https://www.selenium.dev/selenium/web/mouse_interaction.html'
draggable = driver . find_element ( id : 'draggable' )
droppable = driver . find_element ( id : 'droppable' )
driver . action
. drag_and_drop ( draggable , droppable )
. perform
expect ( driver . find_element ( id : 'drop-status' ) . text ) . to include ( 'dropped' )
end
it 'drags by an offset' do
driver . get 'https://www.selenium.dev/selenium/web/mouse_interaction.html'
draggable = driver . find_element ( id : 'draggable' )
start = draggable . rect
finish = driver . find_element ( id : 'droppable' ) . rect
driver . action
. drag_and_drop_by ( draggable , finish . x - start . x , finish . y - start . y )
. perform
expect ( driver . find_element ( id : 'drop-status' ) . text ) . to include ( 'dropped' )
end
end
let clickable = driver . findElement ( By . id ( "clickable" ));
const actions = driver . actions ({ async : true });
await actions . move ({ origin : clickable }). press (). perform ();
Show full example const { By , Builder } = require ( 'selenium-webdriver' );
describe ( 'Click and hold' , function () {
let driver ;
before ( async function () {
driver = new Builder (). forBrowser ( 'chrome' ). build ();
});
after ( async () => await driver . quit ());
it ( 'Mouse move and mouseDown on an element' , async function () {
await driver . get ( 'https://www.selenium.dev/selenium/web/mouse_interaction.html' );
let clickable = driver . findElement ( By . id ( "clickable" ));
const actions = driver . actions ({ async : true });
await actions . move ({ origin : clickable }). press (). perform ();
});
});
val clickable = driver . findElement ( By . id ( "clickable" ))
Actions ( driver )
. clickAndHold ( clickable )
. perform ()
Show full example 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.Rectangle
import org.openqa.selenium.WebElement
import org.openqa.selenium.interactions.Actions
import org.openqa.selenium.interactions.PointerInput
import org.openqa.selenium.interactions.Sequence
import org.openqa.selenium.remote.RemoteWebDriver
import java.time.Duration
import java.util.Collections
class MouseTest : BaseTest () {
@Test
fun clickAndHold () {
driver . get ( "https://www.selenium.dev/selenium/web/mouse_interaction.html" )
val clickable = driver . findElement ( By . id ( "clickable" ))
Actions ( driver )
. clickAndHold ( clickable )
. perform ()
Assertions . assertEquals ( "focused" , driver . findElement ( By . id ( "click-status" )). getText ())
}
@Test
fun clickAndRelease () {
driver . get ( "https://www.selenium.dev/selenium/web/mouse_interaction.html" )
val clickable = driver . findElement ( By . id ( "click" ))
Actions ( driver )
. click ( clickable )
. perform ()
Assertions . assertTrue ( driver . getCurrentUrl () !! . contains ( "resultPage.html" ))
}
@Test
fun rightClick () {
driver . get ( "https://www.selenium.dev/selenium/web/mouse_interaction.html" )
val clickable = driver . findElement ( By . id ( "clickable" ))
Actions ( driver )
. contextClick ( clickable )
. perform ()
Assertions . assertEquals ( "context-clicked" , driver . findElement ( By . id ( "click-status" )). getText ())
}
@Test
fun backClick () {
driver . get ( "https://www.selenium.dev/selenium/web/mouse_interaction.html" )
driver . findElement ( By . id ( "click" )). click ()
Assertions . assertEquals ( driver . getTitle (), "We Arrive Here" )
val mouse = PointerInput ( PointerInput . Kind . MOUSE , "default mouse" )
val actions = Sequence ( mouse , 0 )
. addAction ( mouse . createPointerDown ( PointerInput . MouseButton . BACK . asArg ()))
. addAction ( mouse . createPointerUp ( PointerInput . MouseButton . BACK . asArg ()))
( driver as RemoteWebDriver ). perform ( Collections . singletonList ( actions ))
Assertions . assertEquals ( "BasicMouseInterfaceTest" , driver . getTitle ())
}
@Test
fun forwardClick () {
driver . get ( "https://www.selenium.dev/selenium/web/mouse_interaction.html" )
driver . findElement ( By . id ( "click" )). click ()
driver . navigate (). back ()
Assertions . assertEquals ( driver . getTitle (), "BasicMouseInterfaceTest" )
val mouse = PointerInput ( PointerInput . Kind . MOUSE , "default mouse" )
val actions = Sequence ( mouse , 0 )
. addAction ( mouse . createPointerDown ( PointerInput . MouseButton . FORWARD . asArg ()))
. addAction ( mouse . createPointerUp ( PointerInput . MouseButton . FORWARD . asArg ()))
( driver as RemoteWebDriver ). perform ( Collections . singletonList ( actions ))
Assertions . assertEquals ( "We Arrive Here" , driver . getTitle ())
}
@Test
fun doubleClick () {
driver . get ( "https://www.selenium.dev/selenium/web/mouse_interaction.html" )
val clickable = driver . findElement ( By . id ( "clickable" ))
Actions ( driver )
. doubleClick ( clickable )
. perform ()
Assertions . assertEquals ( "double-clicked" , driver . findElement ( By . id ( "click-status" )). getText ())
}
@Test
fun hovers () {
driver . get ( "https://www.selenium.dev/selenium/web/mouse_interaction.html" )
val hoverable = driver . findElement ( By . id ( "hover" ))
Actions ( driver )
. moveToElement ( hoverable )
. perform ()
Assertions . assertEquals ( "hovered" , driver . findElement ( By . id ( "move-status" )). getText ())
}
@Test
fun moveByOffsetFromElement () {
driver . get ( "https://www.selenium.dev/selenium/web/mouse_interaction.html" )
driver . manage (). window (). fullscreen ()
val tracker = driver . findElement ( By . id ( "mouse-tracker" ))
Actions ( driver )
. moveToElement ( tracker , 8 , 0 )
. perform ()
val result = driver . findElement ( By . id ( "relative-location" )). getText (). split ( ", " )
Assertions . assertTrue ( Math . abs ( Integer . parseInt ( result [ 0 ]) - 100 - 8 ) < 2 )
}
@Test
fun moveByOffsetFromViewport () {
driver . get ( "https://www.selenium.dev/selenium/web/mouse_interaction.html" )
val mouse = PointerInput ( PointerInput . Kind . MOUSE , "default mouse" )
val actions = Sequence ( mouse , 0 )
. addAction ( mouse . createPointerMove ( Duration . ZERO , PointerInput . Origin . viewport (), 8 , 12 ))
( driver as RemoteWebDriver ). perform ( Collections . singletonList ( actions ))
val result = driver . findElement ( By . id ( "absolute-location" )). getText (). split ( ", " )
Assertions . assertTrue ( Math . abs ( Integer . parseInt ( result [ 0 ]) - 8 ) < 2 )
Assertions . assertTrue ( Math . abs ( Integer . parseInt ( result [ 1 ]) - 12 ) < 2 )
}
@Test
fun moveByOffsetFromCurrentPointer () {
driver . get ( "https://www.selenium.dev/selenium/web/mouse_interaction.html" )
val mouse = PointerInput ( PointerInput . Kind . MOUSE , "default mouse" )
val actions = Sequence ( mouse , 0 )
. addAction ( mouse . createPointerMove ( Duration . ZERO , PointerInput . Origin . viewport (), 8 , 11 ))
( driver as RemoteWebDriver ). perform ( Collections . singletonList ( actions ))
Actions ( driver )
. moveByOffset ( 13 , 15 )
. perform ()
val result = driver . findElement ( By . id ( "absolute-location" )). getText (). split ( ", " )
Assertions . assertTrue ( Math . abs ( Integer . parseInt ( result [ 0 ]) - 8 - 13 ) < 2 )
Assertions . assertTrue ( Math . abs ( Integer . parseInt ( result [ 1 ]) - 11 - 15 ) < 2 )
}
@Test
fun dragsToElement () {
driver . get ( "https://www.selenium.dev/selenium/web/mouse_interaction.html" )
val draggable = driver . findElement ( By . id ( "draggable" ))
val droppable = driver . findElement ( By . id ( "droppable" ))
Actions ( driver )
. dragAndDrop ( draggable , droppable )
. perform ()
Assertions . assertEquals ( "dropped" , driver . findElement ( By . id ( "drop-status" )). getText ())
}
@Test
fun dragsByOffset () {
driver . get ( "https://www.selenium.dev/selenium/web/mouse_interaction.html" )
val draggable = driver . findElement ( By . id ( "draggable" ))
val start = draggable . getRect ()
val finish = driver . findElement ( By . id ( "droppable" )). getRect ()
Actions ( driver )
. dragAndDropBy ( draggable , finish . getX () - start . getX (), finish . getY () - start . getY ())
. perform ()
Assertions . assertEquals ( "dropped" , driver . findElement ( By . id ( "drop-status" )). getText ())
}
}
Clicar e Liberar Este método combina mover o mouse para o centro de um elemento com a pressão e liberação do botão esquerdo do mouse. Isso é conhecido como “clicar”:
Java
Python
CSharp
Ruby
JavaScript
Kotlin WebElement clickable = driver . findElement ( By . id ( "click" ));
new Actions ( driver )
. click ( clickable )
. perform ();
Show full example 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.Rectangle ;
import org.openqa.selenium.WebElement ;
import org.openqa.selenium.interactions.Actions ;
import org.openqa.selenium.interactions.PointerInput ;
import org.openqa.selenium.interactions.Sequence ;
import org.openqa.selenium.remote.RemoteWebDriver ;
import java.time.Duration ;
import java.util.Collections ;
public class MouseTest extends BaseChromeTest {
@Test
public void clickAndHold () {
driver . get ( "https://www.selenium.dev/selenium/web/mouse_interaction.html" );
WebElement clickable = driver . findElement ( By . id ( "clickable" ));
new Actions ( driver )
. clickAndHold ( clickable )
. perform ();
Assertions . assertEquals ( "focused" , driver . findElement ( By . id ( "click-status" )). getText ());
}
@Test
public void clickAndRelease () {
driver . get ( "https://www.selenium.dev/selenium/web/mouse_interaction.html" );
WebElement clickable = driver . findElement ( By . id ( "click" ));
new Actions ( driver )
. click ( clickable )
. perform ();
Assertions . assertTrue ( driver . getCurrentUrl (). contains ( "resultPage.html" ));
}
@Test
public void rightClick () {
driver . get ( "https://www.selenium.dev/selenium/web/mouse_interaction.html" );
WebElement clickable = driver . findElement ( By . id ( "clickable" ));
new Actions ( driver )
. contextClick ( clickable )
. perform ();
Assertions . assertEquals ( "context-clicked" , driver . findElement ( By . id ( "click-status" )). getText ());
}
@Test
public void backClick () {
driver . get ( "https://www.selenium.dev/selenium/web/mouse_interaction.html" );
driver . findElement ( By . id ( "click" )). click ();
Assertions . assertEquals ( driver . getTitle (), "We Arrive Here" );
PointerInput mouse = new PointerInput ( PointerInput . Kind . MOUSE , "default mouse" );
Sequence actions = new Sequence ( mouse , 0 )
. addAction ( mouse . createPointerDown ( PointerInput . MouseButton . BACK . asArg ()))
. addAction ( mouse . createPointerUp ( PointerInput . MouseButton . BACK . asArg ()));
(( RemoteWebDriver ) driver ). perform ( Collections . singletonList ( actions ));
Assertions . assertEquals ( "BasicMouseInterfaceTest" , driver . getTitle ());
}
@Test
public void forwardClick () {
driver . get ( "https://www.selenium.dev/selenium/web/mouse_interaction.html" );
driver . findElement ( By . id ( "click" )). click ();
driver . navigate (). back ();
Assertions . assertEquals ( driver . getTitle (), "BasicMouseInterfaceTest" );
PointerInput mouse = new PointerInput ( PointerInput . Kind . MOUSE , "default mouse" );
Sequence actions = new Sequence ( mouse , 0 )
. addAction ( mouse . createPointerDown ( PointerInput . MouseButton . FORWARD . asArg ()))
. addAction ( mouse . createPointerUp ( PointerInput . MouseButton . FORWARD . asArg ()));
(( RemoteWebDriver ) driver ). perform ( Collections . singletonList ( actions ));
Assertions . assertEquals ( "We Arrive Here" , driver . getTitle ());
}
@Test
public void doubleClick () {
driver . get ( "https://www.selenium.dev/selenium/web/mouse_interaction.html" );
WebElement clickable = driver . findElement ( By . id ( "clickable" ));
new Actions ( driver )
. doubleClick ( clickable )
. perform ();
Assertions . assertEquals ( "double-clicked" , driver . findElement ( By . id ( "click-status" )). getText ());
}
@Test
public void hovers () {
driver . get ( "https://www.selenium.dev/selenium/web/mouse_interaction.html" );
WebElement hoverable = driver . findElement ( By . id ( "hover" ));
new Actions ( driver )
. moveToElement ( hoverable )
. perform ();
Assertions . assertEquals ( "hovered" , driver . findElement ( By . id ( "move-status" )). getText ());
}
@Test
public void moveByOffsetFromElement () {
driver . get ( "https://www.selenium.dev/selenium/web/mouse_interaction.html" );
driver . manage (). window (). fullscreen ();
WebElement tracker = driver . findElement ( By . id ( "mouse-tracker" ));
new Actions ( driver )
. moveToElement ( tracker , 8 , 0 )
. perform ();
String [] result = driver . findElement ( By . id ( "relative-location" )). getText (). split ( ", " );
Assertions . assertTrue ( Math . abs ( Integer . parseInt ( result [ 0 ] ) - 100 - 8 ) < 2 );
}
@Test
public void moveByOffsetFromViewport () {
driver . get ( "https://www.selenium.dev/selenium/web/mouse_interaction.html" );
PointerInput mouse = new PointerInput ( PointerInput . Kind . MOUSE , "default mouse" );
Sequence actions = new Sequence ( mouse , 0 )
. addAction ( mouse . createPointerMove ( Duration . ZERO , PointerInput . Origin . viewport (), 8 , 12 ));
(( RemoteWebDriver ) driver ). perform ( Collections . singletonList ( actions ));
String [] result = driver . findElement ( By . id ( "absolute-location" )). getText (). split ( ", " );
Assertions . assertTrue ( Math . abs ( Integer . parseInt ( result [ 0 ] ) - 8 ) < 2 );
Assertions . assertTrue ( Math . abs ( Integer . parseInt ( result [ 1 ] ) - 12 ) < 2 );
}
@Test
public void moveByOffsetFromCurrentPointer () {
driver . get ( "https://www.selenium.dev/selenium/web/mouse_interaction.html" );
PointerInput mouse = new PointerInput ( PointerInput . Kind . MOUSE , "default mouse" );
Sequence actions = new Sequence ( mouse , 0 )
. addAction ( mouse . createPointerMove ( Duration . ZERO , PointerInput . Origin . viewport (), 8 , 11 ));
(( RemoteWebDriver ) driver ). perform ( Collections . singletonList ( actions ));
new Actions ( driver )
. moveByOffset ( 13 , 15 )
. perform ();
String [] result = driver . findElement ( By . id ( "absolute-location" )). getText (). split ( ", " );
Assertions . assertTrue ( Math . abs ( Integer . parseInt ( result [ 0 ] ) - 8 - 13 ) < 2 );
Assertions . assertTrue ( Math . abs ( Integer . parseInt ( result [ 1 ] ) - 11 - 15 ) < 2 );
}
@Test
public void dragsToElement () {
driver . get ( "https://www.selenium.dev/selenium/web/mouse_interaction.html" );
WebElement draggable = driver . findElement ( By . id ( "draggable" ));
WebElement droppable = driver . findElement ( By . id ( "droppable" ));
new Actions ( driver )
. dragAndDrop ( draggable , droppable )
. perform ();
Assertions . assertEquals ( "dropped" , driver . findElement ( By . id ( "drop-status" )). getText ());
}
@Test
public void dragsByOffset () {
driver . get ( "https://www.selenium.dev/selenium/web/mouse_interaction.html" );
WebElement draggable = driver . findElement ( By . id ( "draggable" ));
Rectangle start = draggable . getRect ();
Rectangle finish = driver . findElement ( By . id ( "droppable" )). getRect ();
new Actions ( driver )
. dragAndDropBy ( draggable , finish . getX () - start . getX (), finish . getY () - start . getY ())
. perform ();
Assertions . assertEquals ( "dropped" , driver . findElement ( By . id ( "drop-status" )). getText ());
}
}
clickable = driver . find_element ( By . ID , "click" )
ActionChains ( driver ) \
. click ( clickable ) \
. perform ()
Show full example import pytest
from time import sleep
from selenium.webdriver import ActionChains
from selenium.webdriver.common.actions.action_builder import ActionBuilder
from selenium.webdriver.common.actions.mouse_button import MouseButton
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
def test_click_and_hold ( driver ):
driver . get ( 'https://selenium.dev/selenium/web/mouse_interaction.html' )
clickable = driver . find_element ( By . ID , "clickable" )
ActionChains ( driver ) \
. click_and_hold ( clickable ) \
. perform ()
sleep ( 0.5 )
assert driver . find_element ( By . ID , "click-status" ) . text == "focused"
def test_click_and_release ( driver ):
driver . get ( 'https://selenium.dev/selenium/web/mouse_interaction.html' )
clickable = driver . find_element ( By . ID , "click" )
ActionChains ( driver ) \
. click ( clickable ) \
. perform ()
assert "resultPage.html" in driver . current_url
def test_right_click ( driver ):
driver . get ( 'https://selenium.dev/selenium/web/mouse_interaction.html' )
clickable = driver . find_element ( By . ID , "clickable" )
ActionChains ( driver ) \
. context_click ( clickable ) \
. perform ()
sleep ( 0.5 )
assert driver . find_element ( By . ID , "click-status" ) . text == "context-clicked"
def test_back_click_ab ( driver ):
driver . get ( 'https://selenium.dev/selenium/web/mouse_interaction.html' )
driver . find_element ( By . ID , "click" ) . click ()
assert driver . title == "We Arrive Here"
action = ActionBuilder ( driver )
action . pointer_action . pointer_down ( MouseButton . BACK )
action . pointer_action . pointer_up ( MouseButton . BACK )
action . perform ()
assert driver . title == "BasicMouseInterfaceTest"
def test_forward_click_ab ( driver ):
driver . get ( 'https://selenium.dev/selenium/web/mouse_interaction.html' )
driver . find_element ( By . ID , "click" ) . click ()
driver . back ()
assert driver . title == "BasicMouseInterfaceTest"
action = ActionBuilder ( driver )
action . pointer_action . pointer_down ( MouseButton . FORWARD )
action . pointer_action . pointer_up ( MouseButton . FORWARD )
action . perform ()
assert driver . title == "We Arrive Here"
def test_double_click ( driver ):
driver . get ( 'https://selenium.dev/selenium/web/mouse_interaction.html' )
clickable = driver . find_element ( By . ID , "clickable" )
ActionChains ( driver ) \
. double_click ( clickable ) \
. perform ()
assert driver . find_element ( By . ID , "click-status" ) . text == "double-clicked"
def test_hover ( driver ):
driver . get ( 'https://selenium.dev/selenium/web/mouse_interaction.html' )
hoverable = driver . find_element ( By . ID , "hover" )
ActionChains ( driver ) \
. move_to_element ( hoverable ) \
. perform ()
assert driver . find_element ( By . ID , "move-status" ) . text == "hovered"
def test_move_by_offset_from_element ( driver ):
driver . get ( 'https://selenium.dev/selenium/web/mouse_interaction.html' )
mouse_tracker = driver . find_element ( By . ID , "mouse-tracker" )
ActionChains ( driver ) \
. move_to_element_with_offset ( mouse_tracker , 8 , 0 ) \
. perform ()
coordinates = driver . find_element ( By . ID , "relative-location" ) . text . split ( ", " )
assert abs ( int ( coordinates [ 0 ]) - 100 - 8 ) < 2
def test_move_by_offset_from_viewport_origin_ab ( driver ):
driver . get ( 'https://selenium.dev/selenium/web/mouse_interaction.html' )
WebDriverWait ( driver , 10 ) . until ( EC . presence_of_element_located (( By . ID , "absolute-location" )))
action = ActionBuilder ( driver )
action . pointer_action . move_to_location ( 8 , 0 )
action . perform ()
coordinates = driver . find_element ( By . ID , "absolute-location" ) . text . split ( ", " )
assert abs ( int ( coordinates [ 0 ]) - 8 ) < 2
def test_move_by_offset_from_current_pointer_ab ( driver ):
driver . get ( 'https://selenium.dev/selenium/web/mouse_interaction.html' )
action = ActionBuilder ( driver )
action . pointer_action . move_to_location ( 6 , 3 )
action . perform ()
ActionChains ( driver ) \
. move_by_offset ( 13 , 15 ) \
. perform ()
coordinates = driver . find_element ( By . ID , "absolute-location" ) . text . split ( ", " )
assert abs ( int ( coordinates [ 0 ]) - 6 - 13 ) < 2
assert abs ( int ( coordinates [ 1 ]) - 3 - 15 ) < 2
def test_drag_and_drop_onto_element ( driver ):
driver . get ( 'https://selenium.dev/selenium/web/mouse_interaction.html' )
draggable = driver . find_element ( By . ID , "draggable" )
droppable = driver . find_element ( By . ID , "droppable" )
ActionChains ( driver ) \
. drag_and_drop ( draggable , droppable ) \
. perform ()
assert driver . find_element ( By . ID , "drop-status" ) . text == "dropped"
def test_drag_and_drop_by_offset ( driver ):
driver . get ( 'https://selenium.dev/selenium/web/mouse_interaction.html' )
draggable = driver . find_element ( By . ID , "draggable" )
start = draggable . location
finish = driver . find_element ( By . ID , "droppable" ) . location
ActionChains ( driver ) \
. drag_and_drop_by_offset ( draggable , finish [ 'x' ] - start [ 'x' ], finish [ 'y' ] - start [ 'y' ]) \
. perform ()
assert driver . find_element ( By . ID , "drop-status" ) . text == "dropped"
IWebElement clickable = driver . FindElement ( By . Id ( "click" ));
new Actions ( driver )
. Click ( clickable )
. Perform ();
Show full example using System ;
using System.Drawing ;
using Microsoft.VisualStudio.TestTools.UnitTesting ;
using OpenQA.Selenium ;
using OpenQA.Selenium.Interactions ;
namespace SeleniumDocs.ActionsAPI
{
[TestClass]
public class MouseTest : BaseChromeTest
{
[TestMethod]
public void ClickAndHold ()
{
driver . Url = "https://selenium.dev/selenium/web/mouse_interaction.html" ;
IWebElement clickable = driver . FindElement ( By . Id ( "clickable" ));
new Actions ( driver )
. ClickAndHold ( clickable )
. Perform ();
Assert . AreEqual ( "focused" , driver . FindElement ( By . Id ( "click-status" )). Text );
}
[TestMethod]
public void ClickAndRelease ()
{
driver . Url = "https://selenium.dev/selenium/web/mouse_interaction.html" ;
IWebElement clickable = driver . FindElement ( By . Id ( "click" ));
new Actions ( driver )
. Click ( clickable )
. Perform ();
Assert . IsTrue ( driver . Url . Contains ( "resultPage.html" ));
}
[TestMethod]
public void RightClick ()
{
driver . Url = "https://selenium.dev/selenium/web/mouse_interaction.html" ;
IWebElement clickable = driver . FindElement ( By . Id ( "clickable" ));
new Actions ( driver )
. ContextClick ( clickable )
. Perform ();
Assert . AreEqual ( "context-clicked" , driver . FindElement ( By . Id ( "click-status" )). Text );
}
[TestMethod]
public void BackClick ()
{
driver . Url = "https://selenium.dev/selenium/web/mouse_interaction.html" ;
driver . FindElement ( By . Id ( "click" )). Click ();
Assert . AreEqual ( "We Arrive Here" , driver . Title );
ActionBuilder actionBuilder = new ActionBuilder ();
PointerInputDevice mouse = new PointerInputDevice ( PointerKind . Mouse , "default mouse" );
actionBuilder . AddAction ( mouse . CreatePointerDown ( MouseButton . Back ));
actionBuilder . AddAction ( mouse . CreatePointerUp ( MouseButton . Back ));
(( IActionExecutor ) driver ). PerformActions ( actionBuilder . ToActionSequenceList ());
Assert . AreEqual ( "BasicMouseInterfaceTest" , driver . Title );
}
[TestMethod]
public void ForwardClick ()
{
driver . Url = "https://selenium.dev/selenium/web/mouse_interaction.html" ;
driver . FindElement ( By . Id ( "click" )). Click ();
driver . Navigate (). Back ();
Assert . AreEqual ( "BasicMouseInterfaceTest" , driver . Title );
ActionBuilder actionBuilder = new ActionBuilder ();
PointerInputDevice mouse = new PointerInputDevice ( PointerKind . Mouse , "default mouse" );
actionBuilder . AddAction ( mouse . CreatePointerDown ( MouseButton . Forward ));
actionBuilder . AddAction ( mouse . CreatePointerUp ( MouseButton . Forward ));
(( IActionExecutor ) driver ). PerformActions ( actionBuilder . ToActionSequenceList ());
Assert . AreEqual ( "We Arrive Here" , driver . Title );
}
[TestMethod]
public void DoubleClick ()
{
driver . Url = "https://selenium.dev/selenium/web/mouse_interaction.html" ;
IWebElement clickable = driver . FindElement ( By . Id ( "clickable" ));
new Actions ( driver )
. DoubleClick ( clickable )
. Perform ();
Assert . AreEqual ( "double-clicked" , driver . FindElement ( By . Id ( "click-status" )). Text );
}
[TestMethod]
public void Hovers ()
{
driver . Url = "https://selenium.dev/selenium/web/mouse_interaction.html" ;
IWebElement hoverable = driver . FindElement ( By . Id ( "hover" ));
new Actions ( driver )
. MoveToElement ( hoverable )
. Perform ();
Assert . AreEqual ( "hovered" , driver . FindElement ( By . Id ( "move-status" )). Text );
}
[TestMethod]
[Obsolete("Obsolete")]
public void MoveByOffsetFromTopLeftOfElement ()
{
driver . Url = "https://selenium.dev/selenium/web/mouse_interaction.html" ;
IWebElement tracker = driver . FindElement ( By . Id ( "mouse-tracker" ));
new Actions ( driver )
. MoveToElement ( tracker , 8 , 0 )
. Perform ();
string [] result = driver . FindElement ( By . Id ( "relative-location" )). Text . Split ( ", " );
Assert . IsTrue ( Math . Abs ( int . Parse ( result [ 0 ]) - 100 - 8 ) < 2 );
}
[TestMethod]
public void MoveByOffsetFromCenterOfElement ()
{
driver . Url = "https://selenium.dev/selenium/web/mouse_interaction.html" ;
IWebElement tracker = driver . FindElement ( By . Id ( "mouse-tracker" ));
new Actions ( driver )
. MoveToElement ( tracker , 8 , 0 )
. Perform ();
string [] result = driver . FindElement ( By . Id ( "relative-location" )). Text . Split ( ", " );
Assert . IsTrue ( Math . Abs ( int . Parse ( result [ 0 ]) - 100 - 8 ) < 2 );
}
[TestMethod]
public void MoveByOffsetFromViewport ()
{
driver . Url = "https://selenium.dev/selenium/web/mouse_interaction.html" ;
ActionBuilder actionBuilder = new ActionBuilder ();
PointerInputDevice mouse = new PointerInputDevice ( PointerKind . Mouse , "default mouse" );
actionBuilder . AddAction ( mouse . CreatePointerMove ( CoordinateOrigin . Viewport ,
8 , 0 , TimeSpan . Zero ));
(( IActionExecutor ) driver ). PerformActions ( actionBuilder . ToActionSequenceList ());
string [] result = driver . FindElement ( By . Id ( "absolute-location" )). Text . Split ( ", " );
Assert . IsTrue ( Math . Abs ( int . Parse ( result [ 0 ]) - 8 ) < 2 );
}
[TestMethod]
public void MoveByOffsetFromCurrentPointerLocation ()
{
driver . Url = "https://selenium.dev/selenium/web/mouse_interaction.html" ;
ActionBuilder actionBuilder = new ActionBuilder ();
PointerInputDevice mouse = new PointerInputDevice ( PointerKind . Mouse , "default mouse" );
actionBuilder . AddAction ( mouse . CreatePointerMove ( CoordinateOrigin . Viewport ,
8 , 12 , TimeSpan . Zero ));
(( IActionExecutor ) driver ). PerformActions ( actionBuilder . ToActionSequenceList ());
new Actions ( driver )
. MoveByOffset ( 13 , 15 )
. Perform ();
string [] result = driver . FindElement ( By . Id ( "absolute-location" )). Text . Split ( ", " );
Assert . IsTrue ( Math . Abs ( int . Parse ( result [ 0 ]) - 8 - 13 ) < 2 );
Assert . IsTrue ( Math . Abs ( int . Parse ( result [ 1 ]) - 12 - 15 ) < 2 );
}
[TestMethod]
public void DragToElement ()
{
driver . Url = "https://selenium.dev/selenium/web/mouse_interaction.html" ;
IWebElement draggable = driver . FindElement ( By . Id ( "draggable" ));
IWebElement droppable = driver . FindElement ( By . Id ( "droppable" ));
new Actions ( driver )
. DragAndDrop ( draggable , droppable )
. Perform ();
Assert . AreEqual ( "dropped" , driver . FindElement ( By . Id ( "drop-status" )). Text );
}
[TestMethod]
public void DragByOffset ()
{
driver . Url = "https://selenium.dev/selenium/web/mouse_interaction.html" ;
IWebElement draggable = driver . FindElement ( By . Id ( "draggable" ));
Point start = draggable . Location ;
Point finish = driver . FindElement ( By . Id ( "droppable" )). Location ;
new Actions ( driver )
. DragAndDropToOffset ( draggable , finish . X - start . X , finish . Y - start . Y )
. Perform ();
Assert . AreEqual ( "dropped" , driver . FindElement ( By . Id ( "drop-status" )). Text );
}
}
}
clickable = driver . find_element ( id : 'click' )
driver . action
. click ( clickable )
. perform
Show full example # frozen_string_literal: true
require 'spec_helper'
RSpec . describe 'Mouse' do
let ( :driver ) { start_session }
it 'click and hold' do
driver . get 'https://www.selenium.dev/selenium/web/mouse_interaction.html'
clickable = driver . find_element ( id : 'clickable' )
driver . action
. click_and_hold ( clickable )
. perform
expect ( driver . find_element ( id : 'click-status' ) . text ) . to eq 'focused'
end
it 'click and release' do
driver . get 'https://www.selenium.dev/selenium/web/mouse_interaction.html'
clickable = driver . find_element ( id : 'click' )
driver . action
. click ( clickable )
. perform
expect ( driver . current_url ) . to include 'resultPage.html'
end
describe 'alternate button clicks' do
it 'right click' do
driver . get 'https://www.selenium.dev/selenium/web/mouse_interaction.html'
clickable = driver . find_element ( id : 'clickable' )
driver . action
. context_click ( clickable )
. perform
expect ( driver . find_element ( id : 'click-status' ) . text ) . to eq 'context-clicked'
end
it 'back click' do
driver . get 'https://www.selenium.dev/selenium/web/mouse_interaction.html'
driver . find_element ( id : 'click' ) . click
expect ( driver . title ) . to eq ( 'We Arrive Here' )
driver . action
. pointer_down ( :back )
. pointer_up ( :back )
. perform
expect ( driver . title ) . to eq ( 'BasicMouseInterfaceTest' )
end
it 'forward click' do
driver . get 'https://www.selenium.dev/selenium/web/mouse_interaction.html'
driver . find_element ( id : 'click' ) . click
driver . navigate . back
expect ( driver . title ) . to eq ( 'BasicMouseInterfaceTest' )
driver . action
. pointer_down ( :forward )
. pointer_up ( :forward )
. perform
expect ( driver . title ) . to eq ( 'We Arrive Here' )
end
end
it 'double click' do
driver . get 'https://www.selenium.dev/selenium/web/mouse_interaction.html'
clickable = driver . find_element ( id : 'clickable' )
driver . action
. double_click ( clickable )
. perform
expect ( driver . find_element ( id : 'click-status' ) . text ) . to eq 'double-clicked'
end
it 'hovers' do
driver . get 'https://www.selenium.dev/selenium/web/mouse_interaction.html'
hoverable = driver . find_element ( id : 'hover' )
driver . action
. move_to ( hoverable )
. perform
expect ( driver . find_element ( id : 'move-status' ) . text ) . to eq 'hovered'
end
describe 'move by offset' do
it 'offset from element' do
driver . get 'https://www.selenium.dev/selenium/web/mouse_interaction.html'
driver . action . scroll_to ( driver . find_element ( id : 'bottom' )) . perform
mouse_tracker = driver . find_element ( id : 'mouse-tracker' )
driver . action
. move_to ( mouse_tracker , 8 , 11 )
. perform
rect = mouse_tracker . rect
center_x = rect . width / 2
center_y = rect . height / 2
x_coord , y_coord = driver . find_element ( id : 'relative-location' ) . text . split ( ',' ) . map ( & :to_i )
expect ( x_coord ) . to be_within ( 1 ) . of ( center_x + 8 )
expect ( y_coord ) . to be_within ( 1 ) . of ( center_y + 11 )
end
it 'offset from viewport' do
driver . get 'https://www.selenium.dev/selenium/web/mouse_interaction.html'
driver . action
. move_to_location ( 8 , 12 )
. perform
x_coord , y_coord = driver . find_element ( id : 'absolute-location' ) . text . split ( ',' ) . map ( & :to_i )
expect ( x_coord ) . to be_within ( 1 ) . of ( 8 )
expect ( y_coord ) . to be_within ( 1 ) . of ( 12 )
end
it 'offset from current pointer location' do
driver . get 'https://www.selenium.dev/selenium/web/mouse_interaction.html'
driver . action . move_to_location ( 8 , 11 ) . perform
driver . action
. move_by ( 13 , 15 )
. perform
x_coord , y_coord = driver . find_element ( id : 'absolute-location' ) . text . split ( ',' ) . map ( & :to_i )
expect ( x_coord ) . to be_within ( 1 ) . of ( 8 + 13 )
expect ( y_coord ) . to be_within ( 1 ) . of ( 11 + 15 )
end
end
it 'drags to another element' do
driver . get 'https://www.selenium.dev/selenium/web/mouse_interaction.html'
draggable = driver . find_element ( id : 'draggable' )
droppable = driver . find_element ( id : 'droppable' )
driver . action
. drag_and_drop ( draggable , droppable )
. perform
expect ( driver . find_element ( id : 'drop-status' ) . text ) . to include ( 'dropped' )
end
it 'drags by an offset' do
driver . get 'https://www.selenium.dev/selenium/web/mouse_interaction.html'
draggable = driver . find_element ( id : 'draggable' )
start = draggable . rect
finish = driver . find_element ( id : 'droppable' ) . rect
driver . action
. drag_and_drop_by ( draggable , finish . x - start . x , finish . y - start . y )
. perform
expect ( driver . find_element ( id : 'drop-status' ) . text ) . to include ( 'dropped' )
end
end
let click = driver . findElement ( By . id ( "click" ));
const actions = driver . actions ({ async : true });
await actions . move ({ origin : click }). click (). perform ();
Show full example const { By , Builder } = require ( 'selenium-webdriver' );
describe ( 'Click and release' , function () {
let driver ;
before ( async function () {
driver = new Builder (). forBrowser ( 'chrome' ). build ();
});
after ( async () => await driver . quit ());
it ( 'Mouse move and click on an element' , async function () {
await driver . get ( 'https://www.selenium.dev/selenium/web/mouse_interaction.html' );
let click = driver . findElement ( By . id ( "click" ));
const actions = driver . actions ({ async : true });
await actions . move ({ origin : click }). click (). perform ();
});
});
val clickable = driver . findElement ( By . id ( "click" ))
Actions ( driver )
. click ( clickable )
. perform ()
Show full example 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.Rectangle
import org.openqa.selenium.WebElement
import org.openqa.selenium.interactions.Actions
import org.openqa.selenium.interactions.PointerInput
import org.openqa.selenium.interactions.Sequence
import org.openqa.selenium.remote.RemoteWebDriver
import java.time.Duration
import java.util.Collections
class MouseTest : BaseTest () {
@Test
fun clickAndHold () {
driver . get ( "https://www.selenium.dev/selenium/web/mouse_interaction.html" )
val clickable = driver . findElement ( By . id ( "clickable" ))
Actions ( driver )
. clickAndHold ( clickable )
. perform ()
Assertions . assertEquals ( "focused" , driver . findElement ( By . id ( "click-status" )). getText ())
}
@Test
fun clickAndRelease () {
driver . get ( "https://www.selenium.dev/selenium/web/mouse_interaction.html" )
val clickable = driver . findElement ( By . id ( "click" ))
Actions ( driver )
. click ( clickable )
. perform ()
Assertions . assertTrue ( driver . getCurrentUrl () !! . contains ( "resultPage.html" ))
}
@Test
fun rightClick () {
driver . get ( "https://www.selenium.dev/selenium/web/mouse_interaction.html" )
val clickable = driver . findElement ( By . id ( "clickable" ))
Actions ( driver )
. contextClick ( clickable )
. perform ()
Assertions . assertEquals ( "context-clicked" , driver . findElement ( By . id ( "click-status" )). getText ())
}
@Test
fun backClick () {
driver . get ( "https://www.selenium.dev/selenium/web/mouse_interaction.html" )
driver . findElement ( By . id ( "click" )). click ()
Assertions . assertEquals ( driver . getTitle (), "We Arrive Here" )
val mouse = PointerInput ( PointerInput . Kind . MOUSE , "default mouse" )
val actions = Sequence ( mouse , 0 )
. addAction ( mouse . createPointerDown ( PointerInput . MouseButton . BACK . asArg ()))
. addAction ( mouse . createPointerUp ( PointerInput . MouseButton . BACK . asArg ()))
( driver as RemoteWebDriver ). perform ( Collections . singletonList ( actions ))
Assertions . assertEquals ( "BasicMouseInterfaceTest" , driver . getTitle ())
}
@Test
fun forwardClick () {
driver . get ( "https://www.selenium.dev/selenium/web/mouse_interaction.html" )
driver . findElement ( By . id ( "click" )). click ()
driver . navigate (). back ()
Assertions . assertEquals ( driver . getTitle (), "BasicMouseInterfaceTest" )
val mouse = PointerInput ( PointerInput . Kind . MOUSE , "default mouse" )
val actions = Sequence ( mouse , 0 )
. addAction ( mouse . createPointerDown ( PointerInput . MouseButton . FORWARD . asArg ()))
. addAction ( mouse . createPointerUp ( PointerInput . MouseButton . FORWARD . asArg ()))
( driver as RemoteWebDriver ). perform ( Collections . singletonList ( actions ))
Assertions . assertEquals ( "We Arrive Here" , driver . getTitle ())
}
@Test
fun doubleClick () {
driver . get ( "https://www.selenium.dev/selenium/web/mouse_interaction.html" )
val clickable = driver . findElement ( By . id ( "clickable" ))
Actions ( driver )
. doubleClick ( clickable )
. perform ()
Assertions . assertEquals ( "double-clicked" , driver . findElement ( By . id ( "click-status" )). getText ())
}
@Test
fun hovers () {
driver . get ( "https://www.selenium.dev/selenium/web/mouse_interaction.html" )
val hoverable = driver . findElement ( By . id ( "hover" ))
Actions ( driver )
. moveToElement ( hoverable )
. perform ()
Assertions . assertEquals ( "hovered" , driver . findElement ( By . id ( "move-status" )). getText ())
}
@Test
fun moveByOffsetFromElement () {
driver . get ( "https://www.selenium.dev/selenium/web/mouse_interaction.html" )
driver . manage (). window (). fullscreen ()
val tracker = driver . findElement ( By . id ( "mouse-tracker" ))
Actions ( driver )
. moveToElement ( tracker , 8 , 0 )
. perform ()
val result = driver . findElement ( By . id ( "relative-location" )). getText (). split ( ", " )
Assertions . assertTrue ( Math . abs ( Integer . parseInt ( result [ 0 ]) - 100 - 8 ) < 2 )
}
@Test
fun moveByOffsetFromViewport () {
driver . get ( "https://www.selenium.dev/selenium/web/mouse_interaction.html" )
val mouse = PointerInput ( PointerInput . Kind . MOUSE , "default mouse" )
val actions = Sequence ( mouse , 0 )
. addAction ( mouse . createPointerMove ( Duration . ZERO , PointerInput . Origin . viewport (), 8 , 12 ))
( driver as RemoteWebDriver ). perform ( Collections . singletonList ( actions ))
val result = driver . findElement ( By . id ( "absolute-location" )). getText (). split ( ", " )
Assertions . assertTrue ( Math . abs ( Integer . parseInt ( result [ 0 ]) - 8 ) < 2 )
Assertions . assertTrue ( Math . abs ( Integer . parseInt ( result [ 1 ]) - 12 ) < 2 )
}
@Test
fun moveByOffsetFromCurrentPointer () {
driver . get ( "https://www.selenium.dev/selenium/web/mouse_interaction.html" )
val mouse = PointerInput ( PointerInput . Kind . MOUSE , "default mouse" )
val actions = Sequence ( mouse , 0 )
. addAction ( mouse . createPointerMove ( Duration . ZERO , PointerInput . Origin . viewport (), 8 , 11 ))
( driver as RemoteWebDriver ). perform ( Collections . singletonList ( actions ))
Actions ( driver )
. moveByOffset ( 13 , 15 )
. perform ()
val result = driver . findElement ( By . id ( "absolute-location" )). getText (). split ( ", " )
Assertions . assertTrue ( Math . abs ( Integer . parseInt ( result [ 0 ]) - 8 - 13 ) < 2 )
Assertions . assertTrue ( Math . abs ( Integer . parseInt ( result [ 1 ]) - 11 - 15 ) < 2 )
}
@Test
fun dragsToElement () {
driver . get ( "https://www.selenium.dev/selenium/web/mouse_interaction.html" )
val draggable = driver . findElement ( By . id ( "draggable" ))
val droppable = driver . findElement ( By . id ( "droppable" ))
Actions ( driver )
. dragAndDrop ( draggable , droppable )
. perform ()
Assertions . assertEquals ( "dropped" , driver . findElement ( By . id ( "drop-status" )). getText ())
}
@Test
fun dragsByOffset () {
driver . get ( "https://www.selenium.dev/selenium/web/mouse_interaction.html" )
val draggable = driver . findElement ( By . id ( "draggable" ))
val start = draggable . getRect ()
val finish = driver . findElement ( By . id ( "droppable" )). getRect ()
Actions ( driver )
. dragAndDropBy ( draggable , finish . getX () - start . getX (), finish . getY () - start . getY ())
. perform ()
Assertions . assertEquals ( "dropped" , driver . findElement ( By . id ( "drop-status" )). getText ())
}
}
Existem um total de 5 botões definidos para um mouse:
0 — Botão Esquerdo (o padrão) 1 — Botão do Meio (atualmente não suportado) 2 — Botão Direito 3 — Botão X1 (Voltar) 4 — Botão X2 (Avançar) Context Click Este método combina mover o mouse para o centro de um elemento com a pressão e liberação do botão direito do mouse (botão 2). Isso é conhecido como “clicar com o botão direito” ou “menu de contexto”
Java
Python
CSharp
Ruby
JavaScript
Kotlin WebElement clickable = driver . findElement ( By . id ( "clickable" ));
new Actions ( driver )
. contextClick ( clickable )
. perform ();
Show full example 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.Rectangle ;
import org.openqa.selenium.WebElement ;
import org.openqa.selenium.interactions.Actions ;
import org.openqa.selenium.interactions.PointerInput ;
import org.openqa.selenium.interactions.Sequence ;
import org.openqa.selenium.remote.RemoteWebDriver ;
import java.time.Duration ;
import java.util.Collections ;
public class MouseTest extends BaseChromeTest {
@Test
public void clickAndHold () {
driver . get ( "https://www.selenium.dev/selenium/web/mouse_interaction.html" );
WebElement clickable = driver . findElement ( By . id ( "clickable" ));
new Actions ( driver )
. clickAndHold ( clickable )
. perform ();
Assertions . assertEquals ( "focused" , driver . findElement ( By . id ( "click-status" )). getText ());
}
@Test
public void clickAndRelease () {
driver . get ( "https://www.selenium.dev/selenium/web/mouse_interaction.html" );
WebElement clickable = driver . findElement ( By . id ( "click" ));
new Actions ( driver )
. click ( clickable )
. perform ();
Assertions . assertTrue ( driver . getCurrentUrl (). contains ( "resultPage.html" ));
}
@Test
public void rightClick () {
driver . get ( "https://www.selenium.dev/selenium/web/mouse_interaction.html" );
WebElement clickable = driver . findElement ( By . id ( "clickable" ));
new Actions ( driver )
. contextClick ( clickable )
. perform ();
Assertions . assertEquals ( "context-clicked" , driver . findElement ( By . id ( "click-status" )). getText ());
}
@Test
public void backClick () {
driver . get ( "https://www.selenium.dev/selenium/web/mouse_interaction.html" );
driver . findElement ( By . id ( "click" )). click ();
Assertions . assertEquals ( driver . getTitle (), "We Arrive Here" );
PointerInput mouse = new PointerInput ( PointerInput . Kind . MOUSE , "default mouse" );
Sequence actions = new Sequence ( mouse , 0 )
. addAction ( mouse . createPointerDown ( PointerInput . MouseButton . BACK . asArg ()))
. addAction ( mouse . createPointerUp ( PointerInput . MouseButton . BACK . asArg ()));
(( RemoteWebDriver ) driver ). perform ( Collections . singletonList ( actions ));
Assertions . assertEquals ( "BasicMouseInterfaceTest" , driver . getTitle ());
}
@Test
public void forwardClick () {
driver . get ( "https://www.selenium.dev/selenium/web/mouse_interaction.html" );
driver . findElement ( By . id ( "click" )). click ();
driver . navigate (). back ();
Assertions . assertEquals ( driver . getTitle (), "BasicMouseInterfaceTest" );
PointerInput mouse = new PointerInput ( PointerInput . Kind . MOUSE , "default mouse" );
Sequence actions = new Sequence ( mouse , 0 )
. addAction ( mouse . createPointerDown ( PointerInput . MouseButton . FORWARD . asArg ()))
. addAction ( mouse . createPointerUp ( PointerInput . MouseButton . FORWARD . asArg ()));
(( RemoteWebDriver ) driver ). perform ( Collections . singletonList ( actions ));
Assertions . assertEquals ( "We Arrive Here" , driver . getTitle ());
}
@Test
public void doubleClick () {
driver . get ( "https://www.selenium.dev/selenium/web/mouse_interaction.html" );
WebElement clickable = driver . findElement ( By . id ( "clickable" ));
new Actions ( driver )
. doubleClick ( clickable )
. perform ();
Assertions . assertEquals ( "double-clicked" , driver . findElement ( By . id ( "click-status" )). getText ());
}
@Test
public void hovers () {
driver . get ( "https://www.selenium.dev/selenium/web/mouse_interaction.html" );
WebElement hoverable = driver . findElement ( By . id ( "hover" ));
new Actions ( driver )
. moveToElement ( hoverable )
. perform ();
Assertions . assertEquals ( "hovered" , driver . findElement ( By . id ( "move-status" )). getText ());
}
@Test
public void moveByOffsetFromElement () {
driver . get ( "https://www.selenium.dev/selenium/web/mouse_interaction.html" );
driver . manage (). window (). fullscreen ();
WebElement tracker = driver . findElement ( By . id ( "mouse-tracker" ));
new Actions ( driver )
. moveToElement ( tracker , 8 , 0 )
. perform ();
String [] result = driver . findElement ( By . id ( "relative-location" )). getText (). split ( ", " );
Assertions . assertTrue ( Math . abs ( Integer . parseInt ( result [ 0 ] ) - 100 - 8 ) < 2 );
}
@Test
public void moveByOffsetFromViewport () {
driver . get ( "https://www.selenium.dev/selenium/web/mouse_interaction.html" );
PointerInput mouse = new PointerInput ( PointerInput . Kind . MOUSE , "default mouse" );
Sequence actions = new Sequence ( mouse , 0 )
. addAction ( mouse . createPointerMove ( Duration . ZERO , PointerInput . Origin . viewport (), 8 , 12 ));
(( RemoteWebDriver ) driver ). perform ( Collections . singletonList ( actions ));
String [] result = driver . findElement ( By . id ( "absolute-location" )). getText (). split ( ", " );
Assertions . assertTrue ( Math . abs ( Integer . parseInt ( result [ 0 ] ) - 8 ) < 2 );
Assertions . assertTrue ( Math . abs ( Integer . parseInt ( result [ 1 ] ) - 12 ) < 2 );
}
@Test
public void moveByOffsetFromCurrentPointer () {
driver . get ( "https://www.selenium.dev/selenium/web/mouse_interaction.html" );
PointerInput mouse = new PointerInput ( PointerInput . Kind . MOUSE , "default mouse" );
Sequence actions = new Sequence ( mouse , 0 )
. addAction ( mouse . createPointerMove ( Duration . ZERO , PointerInput . Origin . viewport (), 8 , 11 ));
(( RemoteWebDriver ) driver ). perform ( Collections . singletonList ( actions ));
new Actions ( driver )
. moveByOffset ( 13 , 15 )
. perform ();
String [] result = driver . findElement ( By . id ( "absolute-location" )). getText (). split ( ", " );
Assertions . assertTrue ( Math . abs ( Integer . parseInt ( result [ 0 ] ) - 8 - 13 ) < 2 );
Assertions . assertTrue ( Math . abs ( Integer . parseInt ( result [ 1 ] ) - 11 - 15 ) < 2 );
}
@Test
public void dragsToElement () {
driver . get ( "https://www.selenium.dev/selenium/web/mouse_interaction.html" );
WebElement draggable = driver . findElement ( By . id ( "draggable" ));
WebElement droppable = driver . findElement ( By . id ( "droppable" ));
new Actions ( driver )
. dragAndDrop ( draggable , droppable )
. perform ();
Assertions . assertEquals ( "dropped" , driver . findElement ( By . id ( "drop-status" )). getText ());
}
@Test
public void dragsByOffset () {
driver . get ( "https://www.selenium.dev/selenium/web/mouse_interaction.html" );
WebElement draggable = driver . findElement ( By . id ( "draggable" ));
Rectangle start = draggable . getRect ();
Rectangle finish = driver . findElement ( By . id ( "droppable" )). getRect ();
new Actions ( driver )
. dragAndDropBy ( draggable , finish . getX () - start . getX (), finish . getY () - start . getY ())
. perform ();
Assertions . assertEquals ( "dropped" , driver . findElement ( By . id ( "drop-status" )). getText ());
}
}
clickable = driver . find_element ( By . ID , "clickable" )
ActionChains ( driver ) \
. context_click ( clickable ) \
. perform ()
Show full example import pytest
from time import sleep
from selenium.webdriver import ActionChains
from selenium.webdriver.common.actions.action_builder import ActionBuilder
from selenium.webdriver.common.actions.mouse_button import MouseButton
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
def test_click_and_hold ( driver ):
driver . get ( 'https://selenium.dev/selenium/web/mouse_interaction.html' )
clickable = driver . find_element ( By . ID , "clickable" )
ActionChains ( driver ) \
. click_and_hold ( clickable ) \
. perform ()
sleep ( 0.5 )
assert driver . find_element ( By . ID , "click-status" ) . text == "focused"
def test_click_and_release ( driver ):
driver . get ( 'https://selenium.dev/selenium/web/mouse_interaction.html' )
clickable = driver . find_element ( By . ID , "click" )
ActionChains ( driver ) \
. click ( clickable ) \
. perform ()
assert "resultPage.html" in driver . current_url
def test_right_click ( driver ):
driver . get ( 'https://selenium.dev/selenium/web/mouse_interaction.html' )
clickable = driver . find_element ( By . ID , "clickable" )
ActionChains ( driver ) \
. context_click ( clickable ) \
. perform ()
sleep ( 0.5 )
assert driver . find_element ( By . ID , "click-status" ) . text == "context-clicked"
def test_back_click_ab ( driver ):
driver . get ( 'https://selenium.dev/selenium/web/mouse_interaction.html' )
driver . find_element ( By . ID , "click" ) . click ()
assert driver . title == "We Arrive Here"
action = ActionBuilder ( driver )
action . pointer_action . pointer_down ( MouseButton . BACK )
action . pointer_action . pointer_up ( MouseButton . BACK )
action . perform ()
assert driver . title == "BasicMouseInterfaceTest"
def test_forward_click_ab ( driver ):
driver . get ( 'https://selenium.dev/selenium/web/mouse_interaction.html' )
driver . find_element ( By . ID , "click" ) . click ()
driver . back ()
assert driver . title == "BasicMouseInterfaceTest"
action = ActionBuilder ( driver )
action . pointer_action . pointer_down ( MouseButton . FORWARD )
action . pointer_action . pointer_up ( MouseButton . FORWARD )
action . perform ()
assert driver . title == "We Arrive Here"
def test_double_click ( driver ):
driver . get ( 'https://selenium.dev/selenium/web/mouse_interaction.html' )
clickable = driver . find_element ( By . ID , "clickable" )
ActionChains ( driver ) \
. double_click ( clickable ) \
. perform ()
assert driver . find_element ( By . ID , "click-status" ) . text == "double-clicked"
def test_hover ( driver ):
driver . get ( 'https://selenium.dev/selenium/web/mouse_interaction.html' )
hoverable = driver . find_element ( By . ID , "hover" )
ActionChains ( driver ) \
. move_to_element ( hoverable ) \
. perform ()
assert driver . find_element ( By . ID , "move-status" ) . text == "hovered"
def test_move_by_offset_from_element ( driver ):
driver . get ( 'https://selenium.dev/selenium/web/mouse_interaction.html' )
mouse_tracker = driver . find_element ( By . ID , "mouse-tracker" )
ActionChains ( driver ) \
. move_to_element_with_offset ( mouse_tracker , 8 , 0 ) \
. perform ()
coordinates = driver . find_element ( By . ID , "relative-location" ) . text . split ( ", " )
assert abs ( int ( coordinates [ 0 ]) - 100 - 8 ) < 2
def test_move_by_offset_from_viewport_origin_ab ( driver ):
driver . get ( 'https://selenium.dev/selenium/web/mouse_interaction.html' )
WebDriverWait ( driver , 10 ) . until ( EC . presence_of_element_located (( By . ID , "absolute-location" )))
action = ActionBuilder ( driver )
action . pointer_action . move_to_location ( 8 , 0 )
action . perform ()
coordinates = driver . find_element ( By . ID , "absolute-location" ) . text . split ( ", " )
assert abs ( int ( coordinates [ 0 ]) - 8 ) < 2
def test_move_by_offset_from_current_pointer_ab ( driver ):
driver . get ( 'https://selenium.dev/selenium/web/mouse_interaction.html' )
action = ActionBuilder ( driver )
action . pointer_action . move_to_location ( 6 , 3 )
action . perform ()
ActionChains ( driver ) \
. move_by_offset ( 13 , 15 ) \
. perform ()
coordinates = driver . find_element ( By . ID , "absolute-location" ) . text . split ( ", " )
assert abs ( int ( coordinates [ 0 ]) - 6 - 13 ) < 2
assert abs ( int ( coordinates [ 1 ]) - 3 - 15 ) < 2
def test_drag_and_drop_onto_element ( driver ):
driver . get ( 'https://selenium.dev/selenium/web/mouse_interaction.html' )
draggable = driver . find_element ( By . ID , "draggable" )
droppable = driver . find_element ( By . ID , "droppable" )
ActionChains ( driver ) \
. drag_and_drop ( draggable , droppable ) \
. perform ()
assert driver . find_element ( By . ID , "drop-status" ) . text == "dropped"
def test_drag_and_drop_by_offset ( driver ):
driver . get ( 'https://selenium.dev/selenium/web/mouse_interaction.html' )
draggable = driver . find_element ( By . ID , "draggable" )
start = draggable . location
finish = driver . find_element ( By . ID , "droppable" ) . location
ActionChains ( driver ) \
. drag_and_drop_by_offset ( draggable , finish [ 'x' ] - start [ 'x' ], finish [ 'y' ] - start [ 'y' ]) \
. perform ()
assert driver . find_element ( By . ID , "drop-status" ) . text == "dropped"
IWebElement clickable = driver . FindElement ( By . Id ( "clickable" ));
new Actions ( driver )
. ContextClick ( clickable )
. Perform ();
Show full example using System ;
using System.Drawing ;
using Microsoft.VisualStudio.TestTools.UnitTesting ;
using OpenQA.Selenium ;
using OpenQA.Selenium.Interactions ;
namespace SeleniumDocs.ActionsAPI
{
[TestClass]
public class MouseTest : BaseChromeTest
{
[TestMethod]
public void ClickAndHold ()
{
driver . Url = "https://selenium.dev/selenium/web/mouse_interaction.html" ;
IWebElement clickable = driver . FindElement ( By . Id ( "clickable" ));
new Actions ( driver )
. ClickAndHold ( clickable )
. Perform ();
Assert . AreEqual ( "focused" , driver . FindElement ( By . Id ( "click-status" )). Text );
}
[TestMethod]
public void ClickAndRelease ()
{
driver . Url = "https://selenium.dev/selenium/web/mouse_interaction.html" ;
IWebElement clickable = driver . FindElement ( By . Id ( "click" ));
new Actions ( driver )
. Click ( clickable )
. Perform ();
Assert . IsTrue ( driver . Url . Contains ( "resultPage.html" ));
}
[TestMethod]
public void RightClick ()
{
driver . Url = "https://selenium.dev/selenium/web/mouse_interaction.html" ;
IWebElement clickable = driver . FindElement ( By . Id ( "clickable" ));
new Actions ( driver )
. ContextClick ( clickable )
. Perform ();
Assert . AreEqual ( "context-clicked" , driver . FindElement ( By . Id ( "click-status" )). Text );
}
[TestMethod]
public void BackClick ()
{
driver . Url = "https://selenium.dev/selenium/web/mouse_interaction.html" ;
driver . FindElement ( By . Id ( "click" )). Click ();
Assert . AreEqual ( "We Arrive Here" , driver . Title );
ActionBuilder actionBuilder = new ActionBuilder ();
PointerInputDevice mouse = new PointerInputDevice ( PointerKind . Mouse , "default mouse" );
actionBuilder . AddAction ( mouse . CreatePointerDown ( MouseButton . Back ));
actionBuilder . AddAction ( mouse . CreatePointerUp ( MouseButton . Back ));
(( IActionExecutor ) driver ). PerformActions ( actionBuilder . ToActionSequenceList ());
Assert . AreEqual ( "BasicMouseInterfaceTest" , driver . Title );
}
[TestMethod]
public void ForwardClick ()
{
driver . Url = "https://selenium.dev/selenium/web/mouse_interaction.html" ;
driver . FindElement ( By . Id ( "click" )). Click ();
driver . Navigate (). Back ();
Assert . AreEqual ( "BasicMouseInterfaceTest" , driver . Title );
ActionBuilder actionBuilder = new ActionBuilder ();
PointerInputDevice mouse = new PointerInputDevice ( PointerKind . Mouse , "default mouse" );
actionBuilder . AddAction ( mouse . CreatePointerDown ( MouseButton . Forward ));
actionBuilder . AddAction ( mouse . CreatePointerUp ( MouseButton . Forward ));
(( IActionExecutor ) driver ). PerformActions ( actionBuilder . ToActionSequenceList ());
Assert . AreEqual ( "We Arrive Here" , driver . Title );
}
[TestMethod]
public void DoubleClick ()
{
driver . Url = "https://selenium.dev/selenium/web/mouse_interaction.html" ;
IWebElement clickable = driver . FindElement ( By . Id ( "clickable" ));
new Actions ( driver )
. DoubleClick ( clickable )
. Perform ();
Assert . AreEqual ( "double-clicked" , driver . FindElement ( By . Id ( "click-status" )). Text );
}
[TestMethod]
public void Hovers ()
{
driver . Url = "https://selenium.dev/selenium/web/mouse_interaction.html" ;
IWebElement hoverable = driver . FindElement ( By . Id ( "hover" ));
new Actions ( driver )
. MoveToElement ( hoverable )
. Perform ();
Assert . AreEqual ( "hovered" , driver . FindElement ( By . Id ( "move-status" )). Text );
}
[TestMethod]
[Obsolete("Obsolete")]
public void MoveByOffsetFromTopLeftOfElement ()
{
driver . Url = "https://selenium.dev/selenium/web/mouse_interaction.html" ;
IWebElement tracker = driver . FindElement ( By . Id ( "mouse-tracker" ));
new Actions ( driver )
. MoveToElement ( tracker , 8 , 0 )
. Perform ();
string [] result = driver . FindElement ( By . Id ( "relative-location" )). Text . Split ( ", " );
Assert . IsTrue ( Math . Abs ( int . Parse ( result [ 0 ]) - 100 - 8 ) < 2 );
}
[TestMethod]
public void MoveByOffsetFromCenterOfElement ()
{
driver . Url = "https://selenium.dev/selenium/web/mouse_interaction.html" ;
IWebElement tracker = driver . FindElement ( By . Id ( "mouse-tracker" ));
new Actions ( driver )
. MoveToElement ( tracker , 8 , 0 )
. Perform ();
string [] result = driver . FindElement ( By . Id ( "relative-location" )). Text . Split ( ", " );
Assert . IsTrue ( Math . Abs ( int . Parse ( result [ 0 ]) - 100 - 8 ) < 2 );
}
[TestMethod]
public void MoveByOffsetFromViewport ()
{
driver . Url = "https://selenium.dev/selenium/web/mouse_interaction.html" ;
ActionBuilder actionBuilder = new ActionBuilder ();
PointerInputDevice mouse = new PointerInputDevice ( PointerKind . Mouse , "default mouse" );
actionBuilder . AddAction ( mouse . CreatePointerMove ( CoordinateOrigin . Viewport ,
8 , 0 , TimeSpan . Zero ));
(( IActionExecutor ) driver ). PerformActions ( actionBuilder . ToActionSequenceList ());
string [] result = driver . FindElement ( By . Id ( "absolute-location" )). Text . Split ( ", " );
Assert . IsTrue ( Math . Abs ( int . Parse ( result [ 0 ]) - 8 ) < 2 );
}
[TestMethod]
public void MoveByOffsetFromCurrentPointerLocation ()
{
driver . Url = "https://selenium.dev/selenium/web/mouse_interaction.html" ;
ActionBuilder actionBuilder = new ActionBuilder ();
PointerInputDevice mouse = new PointerInputDevice ( PointerKind . Mouse , "default mouse" );
actionBuilder . AddAction ( mouse . CreatePointerMove ( CoordinateOrigin . Viewport ,
8 , 12 , TimeSpan . Zero ));
(( IActionExecutor ) driver ). PerformActions ( actionBuilder . ToActionSequenceList ());
new Actions ( driver )
. MoveByOffset ( 13 , 15 )
. Perform ();
string [] result = driver . FindElement ( By . Id ( "absolute-location" )). Text . Split ( ", " );
Assert . IsTrue ( Math . Abs ( int . Parse ( result [ 0 ]) - 8 - 13 ) < 2 );
Assert . IsTrue ( Math . Abs ( int . Parse ( result [ 1 ]) - 12 - 15 ) < 2 );
}
[TestMethod]
public void DragToElement ()
{
driver . Url = "https://selenium.dev/selenium/web/mouse_interaction.html" ;
IWebElement draggable = driver . FindElement ( By . Id ( "draggable" ));
IWebElement droppable = driver . FindElement ( By . Id ( "droppable" ));
new Actions ( driver )
. DragAndDrop ( draggable , droppable )
. Perform ();
Assert . AreEqual ( "dropped" , driver . FindElement ( By . Id ( "drop-status" )). Text );
}
[TestMethod]
public void DragByOffset ()
{
driver . Url = "https://selenium.dev/selenium/web/mouse_interaction.html" ;
IWebElement draggable = driver . FindElement ( By . Id ( "draggable" ));
Point start = draggable . Location ;
Point finish = driver . FindElement ( By . Id ( "droppable" )). Location ;
new Actions ( driver )
. DragAndDropToOffset ( draggable , finish . X - start . X , finish . Y - start . Y )
. Perform ();
Assert . AreEqual ( "dropped" , driver . FindElement ( By . Id ( "drop-status" )). Text );
}
}
}
clickable = driver . find_element ( id : 'clickable' )
driver . action
. context_click ( clickable )
. perform
Show full example # frozen_string_literal: true
require 'spec_helper'
RSpec . describe 'Mouse' do
let ( :driver ) { start_session }
it 'click and hold' do
driver . get 'https://www.selenium.dev/selenium/web/mouse_interaction.html'
clickable = driver . find_element ( id : 'clickable' )
driver . action
. click_and_hold ( clickable )
. perform
expect ( driver . find_element ( id : 'click-status' ) . text ) . to eq 'focused'
end
it 'click and release' do
driver . get 'https://www.selenium.dev/selenium/web/mouse_interaction.html'
clickable = driver . find_element ( id : 'click' )
driver . action
. click ( clickable )
. perform
expect ( driver . current_url ) . to include 'resultPage.html'
end
describe 'alternate button clicks' do
it 'right click' do
driver . get 'https://www.selenium.dev/selenium/web/mouse_interaction.html'
clickable = driver . find_element ( id : 'clickable' )
driver . action
. context_click ( clickable )
. perform
expect ( driver . find_element ( id : 'click-status' ) . text ) . to eq 'context-clicked'
end
it 'back click' do
driver . get 'https://www.selenium.dev/selenium/web/mouse_interaction.html'
driver . find_element ( id : 'click' ) . click
expect ( driver . title ) . to eq ( 'We Arrive Here' )
driver . action
. pointer_down ( :back )
. pointer_up ( :back )
. perform
expect ( driver . title ) . to eq ( 'BasicMouseInterfaceTest' )
end
it 'forward click' do
driver . get 'https://www.selenium.dev/selenium/web/mouse_interaction.html'
driver . find_element ( id : 'click' ) . click
driver . navigate . back
expect ( driver . title ) . to eq ( 'BasicMouseInterfaceTest' )
driver . action
. pointer_down ( :forward )
. pointer_up ( :forward )
. perform
expect ( driver . title ) . to eq ( 'We Arrive Here' )
end
end
it 'double click' do
driver . get 'https://www.selenium.dev/selenium/web/mouse_interaction.html'
clickable = driver . find_element ( id : 'clickable' )
driver . action
. double_click ( clickable )
. perform
expect ( driver . find_element ( id : 'click-status' ) . text ) . to eq 'double-clicked'
end
it 'hovers' do
driver . get 'https://www.selenium.dev/selenium/web/mouse_interaction.html'
hoverable = driver . find_element ( id : 'hover' )
driver . action
. move_to ( hoverable )
. perform
expect ( driver . find_element ( id : 'move-status' ) . text ) . to eq 'hovered'
end
describe 'move by offset' do
it 'offset from element' do
driver . get 'https://www.selenium.dev/selenium/web/mouse_interaction.html'
driver . action . scroll_to ( driver . find_element ( id : 'bottom' )) . perform
mouse_tracker = driver . find_element ( id : 'mouse-tracker' )
driver . action
. move_to ( mouse_tracker , 8 , 11 )
. perform
rect = mouse_tracker . rect
center_x = rect . width / 2
center_y = rect . height / 2
x_coord , y_coord = driver . find_element ( id : 'relative-location' ) . text . split ( ',' ) . map ( & :to_i )
expect ( x_coord ) . to be_within ( 1 ) . of ( center_x + 8 )
expect ( y_coord ) . to be_within ( 1 ) . of ( center_y + 11 )
end
it 'offset from viewport' do
driver . get 'https://www.selenium.dev/selenium/web/mouse_interaction.html'
driver . action
. move_to_location ( 8 , 12 )
. perform
x_coord , y_coord = driver . find_element ( id : 'absolute-location' ) . text . split ( ',' ) . map ( & :to_i )
expect ( x_coord ) . to be_within ( 1 ) . of ( 8 )
expect ( y_coord ) . to be_within ( 1 ) . of ( 12 )
end
it 'offset from current pointer location' do
driver . get 'https://www.selenium.dev/selenium/web/mouse_interaction.html'
driver . action . move_to_location ( 8 , 11 ) . perform
driver . action
. move_by ( 13 , 15 )
. perform
x_coord , y_coord = driver . find_element ( id : 'absolute-location' ) . text . split ( ',' ) . map ( & :to_i )
expect ( x_coord ) . to be_within ( 1 ) . of ( 8 + 13 )
expect ( y_coord ) . to be_within ( 1 ) . of ( 11 + 15 )
end
end
it 'drags to another element' do
driver . get 'https://www.selenium.dev/selenium/web/mouse_interaction.html'
draggable = driver . find_element ( id : 'draggable' )
droppable = driver . find_element ( id : 'droppable' )
driver . action
. drag_and_drop ( draggable , droppable )
. perform
expect ( driver . find_element ( id : 'drop-status' ) . text ) . to include ( 'dropped' )
end
it 'drags by an offset' do
driver . get 'https://www.selenium.dev/selenium/web/mouse_interaction.html'
draggable = driver . find_element ( id : 'draggable' )
start = draggable . rect
finish = driver . find_element ( id : 'droppable' ) . rect
driver . action
. drag_and_drop_by ( draggable , finish . x - start . x , finish . y - start . y )
. perform
expect ( driver . find_element ( id : 'drop-status' ) . text ) . to include ( 'dropped' )
end
end
const clickable = driver . findElement ( By . id ( "clickable" ));
const actions = driver . actions ({ async : true });
await actions . contextClick ( clickable ). perform ();
Show full example const { By , Builder } = require ( 'selenium-webdriver' );
const assert = require ( 'assert' );
describe ( 'Right click' , function () {
let driver ;
before ( async function () {
driver = new Builder (). forBrowser ( 'chrome' ). build ();
});
after ( async () => await driver . quit ());
it ( 'Mouse move and right click on an element' , async function () {
await driver . get ( 'https://www.selenium.dev/selenium/web/mouse_interaction.html' );
const clickable = driver . findElement ( By . id ( "clickable" ));
const actions = driver . actions ({ async : true });
await actions . contextClick ( clickable ). perform ();
await driver . sleep ( 500 );
const clicked = await driver . findElement ( By . id ( 'click-status' )). getText ();
assert . deepStrictEqual ( clicked , `context-clicked` )
});
});
val clickable = driver . findElement ( By . id ( "clickable" ))
Actions ( driver )
. contextClick ( clickable )
. perform ()
Show full example 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.Rectangle
import org.openqa.selenium.WebElement
import org.openqa.selenium.interactions.Actions
import org.openqa.selenium.interactions.PointerInput
import org.openqa.selenium.interactions.Sequence
import org.openqa.selenium.remote.RemoteWebDriver
import java.time.Duration
import java.util.Collections
class MouseTest : BaseTest () {
@Test
fun clickAndHold () {
driver . get ( "https://www.selenium.dev/selenium/web/mouse_interaction.html" )
val clickable = driver . findElement ( By . id ( "clickable" ))
Actions ( driver )
. clickAndHold ( clickable )
. perform ()
Assertions . assertEquals ( "focused" , driver . findElement ( By . id ( "click-status" )). getText ())
}
@Test
fun clickAndRelease () {
driver . get ( "https://www.selenium.dev/selenium/web/mouse_interaction.html" )
val clickable = driver . findElement ( By . id ( "click" ))
Actions ( driver )
. click ( clickable )
. perform ()
Assertions . assertTrue ( driver . getCurrentUrl () !! . contains ( "resultPage.html" ))
}
@Test
fun rightClick () {
driver . get ( "https://www.selenium.dev/selenium/web/mouse_interaction.html" )
val clickable = driver . findElement ( By . id ( "clickable" ))
Actions ( driver )
. contextClick ( clickable )
. perform ()
Assertions . assertEquals ( "context-clicked" , driver . findElement ( By . id ( "click-status" )). getText ())
}
@Test
fun backClick () {
driver . get ( "https://www.selenium.dev/selenium/web/mouse_interaction.html" )
driver . findElement ( By . id ( "click" )). click ()
Assertions . assertEquals ( driver . getTitle (), "We Arrive Here" )
val mouse = PointerInput ( PointerInput . Kind . MOUSE , "default mouse" )
val actions = Sequence ( mouse , 0 )
. addAction ( mouse . createPointerDown ( PointerInput . MouseButton . BACK . asArg ()))
. addAction ( mouse . createPointerUp ( PointerInput . MouseButton . BACK . asArg ()))
( driver as RemoteWebDriver ). perform ( Collections . singletonList ( actions ))
Assertions . assertEquals ( "BasicMouseInterfaceTest" , driver . getTitle ())
}
@Test
fun forwardClick () {
driver . get ( "https://www.selenium.dev/selenium/web/mouse_interaction.html" )
driver . findElement ( By . id ( "click" )). click ()
driver . navigate (). back ()
Assertions . assertEquals ( driver . getTitle (), "BasicMouseInterfaceTest" )
val mouse = PointerInput ( PointerInput . Kind . MOUSE , "default mouse" )
val actions = Sequence ( mouse , 0 )
. addAction ( mouse . createPointerDown ( PointerInput . MouseButton . FORWARD . asArg ()))
. addAction ( mouse . createPointerUp ( PointerInput . MouseButton . FORWARD . asArg ()))
( driver as RemoteWebDriver ). perform ( Collections . singletonList ( actions ))
Assertions . assertEquals ( "We Arrive Here" , driver . getTitle ())
}
@Test
fun doubleClick () {
driver . get ( "https://www.selenium.dev/selenium/web/mouse_interaction.html" )
val clickable = driver . findElement ( By . id ( "clickable" ))
Actions ( driver )
. doubleClick ( clickable )
. perform ()
Assertions . assertEquals ( "double-clicked" , driver . findElement ( By . id ( "click-status" )). getText ())
}
@Test
fun hovers () {
driver . get ( "https://www.selenium.dev/selenium/web/mouse_interaction.html" )
val hoverable = driver . findElement ( By . id ( "hover" ))
Actions ( driver )
. moveToElement ( hoverable )
. perform ()
Assertions . assertEquals ( "hovered" , driver . findElement ( By . id ( "move-status" )). getText ())
}
@Test
fun moveByOffsetFromElement () {
driver . get ( "https://www.selenium.dev/selenium/web/mouse_interaction.html" )
driver . manage (). window (). fullscreen ()
val tracker = driver . findElement ( By . id ( "mouse-tracker" ))
Actions ( driver )
. moveToElement ( tracker , 8 , 0 )
. perform ()
val result = driver . findElement ( By . id ( "relative-location" )). getText (). split ( ", " )
Assertions . assertTrue ( Math . abs ( Integer . parseInt ( result [ 0 ]) - 100 - 8 ) < 2 )
}
@Test
fun moveByOffsetFromViewport () {
driver . get ( "https://www.selenium.dev/selenium/web/mouse_interaction.html" )
val mouse = PointerInput ( PointerInput . Kind . MOUSE , "default mouse" )
val actions = Sequence ( mouse , 0 )
. addAction ( mouse . createPointerMove ( Duration . ZERO , PointerInput . Origin . viewport (), 8 , 12 ))
( driver as RemoteWebDriver ). perform ( Collections . singletonList ( actions ))
val result = driver . findElement ( By . id ( "absolute-location" )). getText (). split ( ", " )
Assertions . assertTrue ( Math . abs ( Integer . parseInt ( result [ 0 ]) - 8 ) < 2 )
Assertions . assertTrue ( Math . abs ( Integer . parseInt ( result [ 1 ]) - 12 ) < 2 )
}
@Test
fun moveByOffsetFromCurrentPointer () {
driver . get ( "https://www.selenium.dev/selenium/web/mouse_interaction.html" )
val mouse = PointerInput ( PointerInput . Kind . MOUSE , "default mouse" )
val actions = Sequence ( mouse , 0 )
. addAction ( mouse . createPointerMove ( Duration . ZERO , PointerInput . Origin . viewport (), 8 , 11 ))
( driver as RemoteWebDriver ). perform ( Collections . singletonList ( actions ))
Actions ( driver )
. moveByOffset ( 13 , 15 )
. perform ()
val result = driver . findElement ( By . id ( "absolute-location" )). getText (). split ( ", " )
Assertions . assertTrue ( Math . abs ( Integer . parseInt ( result [ 0 ]) - 8 - 13 ) < 2 )
Assertions . assertTrue ( Math . abs ( Integer . parseInt ( result [ 1 ]) - 11 - 15 ) < 2 )
}
@Test
fun dragsToElement () {
driver . get ( "https://www.selenium.dev/selenium/web/mouse_interaction.html" )
val draggable = driver . findElement ( By . id ( "draggable" ))
val droppable = driver . findElement ( By . id ( "droppable" ))
Actions ( driver )
. dragAndDrop ( draggable , droppable )
. perform ()
Assertions . assertEquals ( "dropped" , driver . findElement ( By . id ( "drop-status" )). getText ())
}
@Test
fun dragsByOffset () {
driver . get ( "https://www.selenium.dev/selenium/web/mouse_interaction.html" )
val draggable = driver . findElement ( By . id ( "draggable" ))
val start = draggable . getRect ()
val finish = driver . findElement ( By . id ( "droppable" )). getRect ()
Actions ( driver )
. dragAndDropBy ( draggable , finish . getX () - start . getX (), finish . getY () - start . getY ())
. perform ()
Assertions . assertEquals ( "dropped" , driver . findElement ( By . id ( "drop-status" )). getText ())
}
}
Click botão de voltar do mouse Este termo pode se referir a um clique com o botão X1 (botão de voltar) do mouse. No entanto, essa terminologia específica pode variar dependendo do contexto.
Java
Python
CSharp
Ruby
JavaScript
Kotlin PointerInput mouse = new PointerInput ( PointerInput . Kind . MOUSE , "default mouse" );
Sequence actions = new Sequence ( mouse , 0 )
. addAction ( mouse . createPointerDown ( PointerInput . MouseButton . BACK . asArg ()))
. addAction ( mouse . createPointerUp ( PointerInput . MouseButton . BACK . asArg ()));
(( RemoteWebDriver ) driver ). perform ( Collections . singletonList ( actions ));
Show full example 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.Rectangle ;
import org.openqa.selenium.WebElement ;
import org.openqa.selenium.interactions.Actions ;
import org.openqa.selenium.interactions.PointerInput ;
import org.openqa.selenium.interactions.Sequence ;
import org.openqa.selenium.remote.RemoteWebDriver ;
import java.time.Duration ;
import java.util.Collections ;
public class MouseTest extends BaseChromeTest {
@Test
public void clickAndHold () {
driver . get ( "https://www.selenium.dev/selenium/web/mouse_interaction.html" );
WebElement clickable = driver . findElement ( By . id ( "clickable" ));
new Actions ( driver )
. clickAndHold ( clickable )
. perform ();
Assertions . assertEquals ( "focused" , driver . findElement ( By . id ( "click-status" )). getText ());
}
@Test
public void clickAndRelease () {
driver . get ( "https://www.selenium.dev/selenium/web/mouse_interaction.html" );
WebElement clickable = driver . findElement ( By . id ( "click" ));
new Actions ( driver )
. click ( clickable )
. perform ();
Assertions . assertTrue ( driver . getCurrentUrl (). contains ( "resultPage.html" ));
}
@Test
public void rightClick () {
driver . get ( "https://www.selenium.dev/selenium/web/mouse_interaction.html" );
WebElement clickable = driver . findElement ( By . id ( "clickable" ));
new Actions ( driver )
. contextClick ( clickable )
. perform ();
Assertions . assertEquals ( "context-clicked" , driver . findElement ( By . id ( "click-status" )). getText ());
}
@Test
public void backClick () {
driver . get ( "https://www.selenium.dev/selenium/web/mouse_interaction.html" );
driver . findElement ( By . id ( "click" )). click ();
Assertions . assertEquals ( driver . getTitle (), "We Arrive Here" );
PointerInput mouse = new PointerInput ( PointerInput . Kind . MOUSE , "default mouse" );
Sequence actions = new Sequence ( mouse , 0 )
. addAction ( mouse . createPointerDown ( PointerInput . MouseButton . BACK . asArg ()))
. addAction ( mouse . createPointerUp ( PointerInput . MouseButton . BACK . asArg ()));
(( RemoteWebDriver ) driver ). perform ( Collections . singletonList ( actions ));
Assertions . assertEquals ( "BasicMouseInterfaceTest" , driver . getTitle ());
}
@Test
public void forwardClick () {
driver . get ( "https://www.selenium.dev/selenium/web/mouse_interaction.html" );
driver . findElement ( By . id ( "click" )). click ();
driver . navigate (). back ();
Assertions . assertEquals ( driver . getTitle (), "BasicMouseInterfaceTest" );
PointerInput mouse = new PointerInput ( PointerInput . Kind . MOUSE , "default mouse" );
Sequence actions = new Sequence ( mouse , 0 )
. addAction ( mouse . createPointerDown ( PointerInput . MouseButton . FORWARD . asArg ()))
. addAction ( mouse . createPointerUp ( PointerInput . MouseButton . FORWARD . asArg ()));
(( RemoteWebDriver ) driver ). perform ( Collections . singletonList ( actions ));
Assertions . assertEquals ( "We Arrive Here" , driver . getTitle ());
}
@Test
public void doubleClick () {
driver . get ( "https://www.selenium.dev/selenium/web/mouse_interaction.html" );
WebElement clickable = driver . findElement ( By . id ( "clickable" ));
new Actions ( driver )
. doubleClick ( clickable )
. perform ();
Assertions . assertEquals ( "double-clicked" , driver . findElement ( By . id ( "click-status" )). getText ());
}
@Test
public void hovers () {
driver . get ( "https://www.selenium.dev/selenium/web/mouse_interaction.html" );
WebElement hoverable = driver . findElement ( By . id ( "hover" ));
new Actions ( driver )
. moveToElement ( hoverable )
. perform ();
Assertions . assertEquals ( "hovered" , driver . findElement ( By . id ( "move-status" )). getText ());
}
@Test
public void moveByOffsetFromElement () {
driver . get ( "https://www.selenium.dev/selenium/web/mouse_interaction.html" );
driver . manage (). window (). fullscreen ();
WebElement tracker = driver . findElement ( By . id ( "mouse-tracker" ));
new Actions ( driver )
. moveToElement ( tracker , 8 , 0 )
. perform ();
String [] result = driver . findElement ( By . id ( "relative-location" )). getText (). split ( ", " );
Assertions . assertTrue ( Math . abs ( Integer . parseInt ( result [ 0 ] ) - 100 - 8 ) < 2 );
}
@Test
public void moveByOffsetFromViewport () {
driver . get ( "https://www.selenium.dev/selenium/web/mouse_interaction.html" );
PointerInput mouse = new PointerInput ( PointerInput . Kind . MOUSE , "default mouse" );
Sequence actions = new Sequence ( mouse , 0 )
. addAction ( mouse . createPointerMove ( Duration . ZERO , PointerInput . Origin . viewport (), 8 , 12 ));
(( RemoteWebDriver ) driver ). perform ( Collections . singletonList ( actions ));
String [] result = driver . findElement ( By . id ( "absolute-location" )). getText (). split ( ", " );
Assertions . assertTrue ( Math . abs ( Integer . parseInt ( result [ 0 ] ) - 8 ) < 2 );
Assertions . assertTrue ( Math . abs ( Integer . parseInt ( result [ 1 ] ) - 12 ) < 2 );
}
@Test
public void moveByOffsetFromCurrentPointer () {
driver . get ( "https://www.selenium.dev/selenium/web/mouse_interaction.html" );
PointerInput mouse = new PointerInput ( PointerInput . Kind . MOUSE , "default mouse" );
Sequence actions = new Sequence ( mouse , 0 )
. addAction ( mouse . createPointerMove ( Duration . ZERO , PointerInput . Origin . viewport (), 8 , 11 ));
(( RemoteWebDriver ) driver ). perform ( Collections . singletonList ( actions ));
new Actions ( driver )
. moveByOffset ( 13 , 15 )
. perform ();
String [] result = driver . findElement ( By . id ( "absolute-location" )). getText (). split ( ", " );
Assertions . assertTrue ( Math . abs ( Integer . parseInt ( result [ 0 ] ) - 8 - 13 ) < 2 );
Assertions . assertTrue ( Math . abs ( Integer . parseInt ( result [ 1 ] ) - 11 - 15 ) < 2 );
}
@Test
public void dragsToElement () {
driver . get ( "https://www.selenium.dev/selenium/web/mouse_interaction.html" );
WebElement draggable = driver . findElement ( By . id ( "draggable" ));
WebElement droppable = driver . findElement ( By . id ( "droppable" ));
new Actions ( driver )
. dragAndDrop ( draggable , droppable )
. perform ();
Assertions . assertEquals ( "dropped" , driver . findElement ( By . id ( "drop-status" )). getText ());
}
@Test
public void dragsByOffset () {
driver . get ( "https://www.selenium.dev/selenium/web/mouse_interaction.html" );
WebElement draggable = driver . findElement ( By . id ( "draggable" ));
Rectangle start = draggable . getRect ();
Rectangle finish = driver . findElement ( By . id ( "droppable" )). getRect ();
new Actions ( driver )
. dragAndDropBy ( draggable , finish . getX () - start . getX (), finish . getY () - start . getY ())
. perform ();
Assertions . assertEquals ( "dropped" , driver . findElement ( By . id ( "drop-status" )). getText ());
}
}
Selenium v4.2
action = ActionBuilder ( driver )
action . pointer_action . pointer_down ( MouseButton . BACK )
action . pointer_action . pointer_up ( MouseButton . BACK )
action . perform ()
Show full example import pytest
from time import sleep
from selenium.webdriver import ActionChains
from selenium.webdriver.common.actions.action_builder import ActionBuilder
from selenium.webdriver.common.actions.mouse_button import MouseButton
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
def test_click_and_hold ( driver ):
driver . get ( 'https://selenium.dev/selenium/web/mouse_interaction.html' )
clickable = driver . find_element ( By . ID , "clickable" )
ActionChains ( driver ) \
. click_and_hold ( clickable ) \
. perform ()
sleep ( 0.5 )
assert driver . find_element ( By . ID , "click-status" ) . text == "focused"
def test_click_and_release ( driver ):
driver . get ( 'https://selenium.dev/selenium/web/mouse_interaction.html' )
clickable = driver . find_element ( By . ID , "click" )
ActionChains ( driver ) \
. click ( clickable ) \
. perform ()
assert "resultPage.html" in driver . current_url
def test_right_click ( driver ):
driver . get ( 'https://selenium.dev/selenium/web/mouse_interaction.html' )
clickable = driver . find_element ( By . ID , "clickable" )
ActionChains ( driver ) \
. context_click ( clickable ) \
. perform ()
sleep ( 0.5 )
assert driver . find_element ( By . ID , "click-status" ) . text == "context-clicked"
def test_back_click_ab ( driver ):
driver . get ( 'https://selenium.dev/selenium/web/mouse_interaction.html' )
driver . find_element ( By . ID , "click" ) . click ()
assert driver . title == "We Arrive Here"
action = ActionBuilder ( driver )
action . pointer_action . pointer_down ( MouseButton . BACK )
action . pointer_action . pointer_up ( MouseButton . BACK )
action . perform ()
assert driver . title == "BasicMouseInterfaceTest"
def test_forward_click_ab ( driver ):
driver . get ( 'https://selenium.dev/selenium/web/mouse_interaction.html' )
driver . find_element ( By . ID , "click" ) . click ()
driver . back ()
assert driver . title == "BasicMouseInterfaceTest"
action = ActionBuilder ( driver )
action . pointer_action . pointer_down ( MouseButton . FORWARD )
action . pointer_action . pointer_up ( MouseButton . FORWARD )
action . perform ()
assert driver . title == "We Arrive Here"
def test_double_click ( driver ):
driver . get ( 'https://selenium.dev/selenium/web/mouse_interaction.html' )
clickable = driver . find_element ( By . ID , "clickable" )
ActionChains ( driver ) \
. double_click ( clickable ) \
. perform ()
assert driver . find_element ( By . ID , "click-status" ) . text == "double-clicked"
def test_hover ( driver ):
driver . get ( 'https://selenium.dev/selenium/web/mouse_interaction.html' )
hoverable = driver . find_element ( By . ID , "hover" )
ActionChains ( driver ) \
. move_to_element ( hoverable ) \
. perform ()
assert driver . find_element ( By . ID , "move-status" ) . text == "hovered"
def test_move_by_offset_from_element ( driver ):
driver . get ( 'https://selenium.dev/selenium/web/mouse_interaction.html' )
mouse_tracker = driver . find_element ( By . ID , "mouse-tracker" )
ActionChains ( driver ) \
. move_to_element_with_offset ( mouse_tracker , 8 , 0 ) \
. perform ()
coordinates = driver . find_element ( By . ID , "relative-location" ) . text . split ( ", " )
assert abs ( int ( coordinates [ 0 ]) - 100 - 8 ) < 2
def test_move_by_offset_from_viewport_origin_ab ( driver ):
driver . get ( 'https://selenium.dev/selenium/web/mouse_interaction.html' )
WebDriverWait ( driver , 10 ) . until ( EC . presence_of_element_located (( By . ID , "absolute-location" )))
action = ActionBuilder ( driver )
action . pointer_action . move_to_location ( 8 , 0 )
action . perform ()
coordinates = driver . find_element ( By . ID , "absolute-location" ) . text . split ( ", " )
assert abs ( int ( coordinates [ 0 ]) - 8 ) < 2
def test_move_by_offset_from_current_pointer_ab ( driver ):
driver . get ( 'https://selenium.dev/selenium/web/mouse_interaction.html' )
action = ActionBuilder ( driver )
action . pointer_action . move_to_location ( 6 , 3 )
action . perform ()
ActionChains ( driver ) \
. move_by_offset ( 13 , 15 ) \
. perform ()
coordinates = driver . find_element ( By . ID , "absolute-location" ) . text . split ( ", " )
assert abs ( int ( coordinates [ 0 ]) - 6 - 13 ) < 2
assert abs ( int ( coordinates [ 1 ]) - 3 - 15 ) < 2
def test_drag_and_drop_onto_element ( driver ):
driver . get ( 'https://selenium.dev/selenium/web/mouse_interaction.html' )
draggable = driver . find_element ( By . ID , "draggable" )
droppable = driver . find_element ( By . ID , "droppable" )
ActionChains ( driver ) \
. drag_and_drop ( draggable , droppable ) \
. perform ()
assert driver . find_element ( By . ID , "drop-status" ) . text == "dropped"
def test_drag_and_drop_by_offset ( driver ):
driver . get ( 'https://selenium.dev/selenium/web/mouse_interaction.html' )
draggable = driver . find_element ( By . ID , "draggable" )
start = draggable . location
finish = driver . find_element ( By . ID , "droppable" ) . location
ActionChains ( driver ) \
. drag_and_drop_by_offset ( draggable , finish [ 'x' ] - start [ 'x' ], finish [ 'y' ] - start [ 'y' ]) \
. perform ()
assert driver . find_element ( By . ID , "drop-status" ) . text == "dropped"
Selenium v4.2
ActionBuilder actionBuilder = new ActionBuilder ();
PointerInputDevice mouse = new PointerInputDevice ( PointerKind . Mouse , "default mouse" );
actionBuilder . AddAction ( mouse . CreatePointerDown ( MouseButton . Back ));
actionBuilder . AddAction ( mouse . CreatePointerUp ( MouseButton . Back ));
(( IActionExecutor ) driver ). PerformActions ( actionBuilder . ToActionSequenceList ());
Show full example using System ;
using System.Drawing ;
using Microsoft.VisualStudio.TestTools.UnitTesting ;
using OpenQA.Selenium ;
using OpenQA.Selenium.Interactions ;
namespace SeleniumDocs.ActionsAPI
{
[TestClass]
public class MouseTest : BaseChromeTest
{
[TestMethod]
public void ClickAndHold ()
{
driver . Url = "https://selenium.dev/selenium/web/mouse_interaction.html" ;
IWebElement clickable = driver . FindElement ( By . Id ( "clickable" ));
new Actions ( driver )
. ClickAndHold ( clickable )
. Perform ();
Assert . AreEqual ( "focused" , driver . FindElement ( By . Id ( "click-status" )). Text );
}
[TestMethod]
public void ClickAndRelease ()
{
driver . Url = "https://selenium.dev/selenium/web/mouse_interaction.html" ;
IWebElement clickable = driver . FindElement ( By . Id ( "click" ));
new Actions ( driver )
. Click ( clickable )
. Perform ();
Assert . IsTrue ( driver . Url . Contains ( "resultPage.html" ));
}
[TestMethod]
public void RightClick ()
{
driver . Url = "https://selenium.dev/selenium/web/mouse_interaction.html" ;
IWebElement clickable = driver . FindElement ( By . Id ( "clickable" ));
new Actions ( driver )
. ContextClick ( clickable )
. Perform ();
Assert . AreEqual ( "context-clicked" , driver . FindElement ( By . Id ( "click-status" )). Text );
}
[TestMethod]
public void BackClick ()
{
driver . Url = "https://selenium.dev/selenium/web/mouse_interaction.html" ;
driver . FindElement ( By . Id ( "click" )). Click ();
Assert . AreEqual ( "We Arrive Here" , driver . Title );
ActionBuilder actionBuilder = new ActionBuilder ();
PointerInputDevice mouse = new PointerInputDevice ( PointerKind . Mouse , "default mouse" );
actionBuilder . AddAction ( mouse . CreatePointerDown ( MouseButton . Back ));
actionBuilder . AddAction ( mouse . CreatePointerUp ( MouseButton . Back ));
(( IActionExecutor ) driver ). PerformActions ( actionBuilder . ToActionSequenceList ());
Assert . AreEqual ( "BasicMouseInterfaceTest" , driver . Title );
}
[TestMethod]
public void ForwardClick ()
{
driver . Url = "https://selenium.dev/selenium/web/mouse_interaction.html" ;
driver . FindElement ( By . Id ( "click" )). Click ();
driver . Navigate (). Back ();
Assert . AreEqual ( "BasicMouseInterfaceTest" , driver . Title );
ActionBuilder actionBuilder = new ActionBuilder ();
PointerInputDevice mouse = new PointerInputDevice ( PointerKind . Mouse , "default mouse" );
actionBuilder . AddAction ( mouse . CreatePointerDown ( MouseButton . Forward ));
actionBuilder . AddAction ( mouse . CreatePointerUp ( MouseButton . Forward ));
(( IActionExecutor ) driver ). PerformActions ( actionBuilder . ToActionSequenceList ());
Assert . AreEqual ( "We Arrive Here" , driver . Title );
}
[TestMethod]
public void DoubleClick ()
{
driver . Url = "https://selenium.dev/selenium/web/mouse_interaction.html" ;
IWebElement clickable = driver . FindElement ( By . Id ( "clickable" ));
new Actions ( driver )
. DoubleClick ( clickable )
. Perform ();
Assert . AreEqual ( "double-clicked" , driver . FindElement ( By . Id ( "click-status" )). Text );
}
[TestMethod]
public void Hovers ()
{
driver . Url = "https://selenium.dev/selenium/web/mouse_interaction.html" ;
IWebElement hoverable = driver . FindElement ( By . Id ( "hover" ));
new Actions ( driver )
. MoveToElement ( hoverable )
. Perform ();
Assert . AreEqual ( "hovered" , driver . FindElement ( By . Id ( "move-status" )). Text );
}
[TestMethod]
[Obsolete("Obsolete")]
public void MoveByOffsetFromTopLeftOfElement ()
{
driver . Url = "https://selenium.dev/selenium/web/mouse_interaction.html" ;
IWebElement tracker = driver . FindElement ( By . Id ( "mouse-tracker" ));
new Actions ( driver )
. MoveToElement ( tracker , 8 , 0 )
. Perform ();
string [] result = driver . FindElement ( By . Id ( "relative-location" )). Text . Split ( ", " );
Assert . IsTrue ( Math . Abs ( int . Parse ( result [ 0 ]) - 100 - 8 ) < 2 );
}
[TestMethod]
public void MoveByOffsetFromCenterOfElement ()
{
driver . Url = "https://selenium.dev/selenium/web/mouse_interaction.html" ;
IWebElement tracker = driver . FindElement ( By . Id ( "mouse-tracker" ));
new Actions ( driver )
. MoveToElement ( tracker , 8 , 0 )
. Perform ();
string [] result = driver . FindElement ( By . Id ( "relative-location" )). Text . Split ( ", " );
Assert . IsTrue ( Math . Abs ( int . Parse ( result [ 0 ]) - 100 - 8 ) < 2 );
}
[TestMethod]
public void MoveByOffsetFromViewport ()
{
driver . Url = "https://selenium.dev/selenium/web/mouse_interaction.html" ;
ActionBuilder actionBuilder = new ActionBuilder ();
PointerInputDevice mouse = new PointerInputDevice ( PointerKind . Mouse , "default mouse" );
actionBuilder . AddAction ( mouse . CreatePointerMove ( CoordinateOrigin . Viewport ,
8 , 0 , TimeSpan . Zero ));
(( IActionExecutor ) driver ). PerformActions ( actionBuilder . ToActionSequenceList ());
string [] result = driver . FindElement ( By . Id ( "absolute-location" )). Text . Split ( ", " );
Assert . IsTrue ( Math . Abs ( int . Parse ( result [ 0 ]) - 8 ) < 2 );
}
[TestMethod]
public void MoveByOffsetFromCurrentPointerLocation ()
{
driver . Url = "https://selenium.dev/selenium/web/mouse_interaction.html" ;
ActionBuilder actionBuilder = new ActionBuilder ();
PointerInputDevice mouse = new PointerInputDevice ( PointerKind . Mouse , "default mouse" );
actionBuilder . AddAction ( mouse . CreatePointerMove ( CoordinateOrigin . Viewport ,
8 , 12 , TimeSpan . Zero ));
(( IActionExecutor ) driver ). PerformActions ( actionBuilder . ToActionSequenceList ());
new Actions ( driver )
. MoveByOffset ( 13 , 15 )
. Perform ();
string [] result = driver . FindElement ( By . Id ( "absolute-location" )). Text . Split ( ", " );
Assert . IsTrue ( Math . Abs ( int . Parse ( result [ 0 ]) - 8 - 13 ) < 2 );
Assert . IsTrue ( Math . Abs ( int . Parse ( result [ 1 ]) - 12 - 15 ) < 2 );
}
[TestMethod]
public void DragToElement ()
{
driver . Url = "https://selenium.dev/selenium/web/mouse_interaction.html" ;
IWebElement draggable = driver . FindElement ( By . Id ( "draggable" ));
IWebElement droppable = driver . FindElement ( By . Id ( "droppable" ));
new Actions ( driver )
. DragAndDrop ( draggable , droppable )
. Perform ();
Assert . AreEqual ( "dropped" , driver . FindElement ( By . Id ( "drop-status" )). Text );
}
[TestMethod]
public void DragByOffset ()
{
driver . Url = "https://selenium.dev/selenium/web/mouse_interaction.html" ;
IWebElement draggable = driver . FindElement ( By . Id ( "draggable" ));
Point start = draggable . Location ;
Point finish = driver . FindElement ( By . Id ( "droppable" )). Location ;
new Actions ( driver )
. DragAndDropToOffset ( draggable , finish . X - start . X , finish . Y - start . Y )
. Perform ();
Assert . AreEqual ( "dropped" , driver . FindElement ( By . Id ( "drop-status" )). Text );
}
}
}
Selenium v4.2
driver . action
. pointer_down ( :back )
. pointer_up ( :back )
. perform
Show full example # frozen_string_literal: true
require 'spec_helper'
RSpec . describe 'Mouse' do
let ( :driver ) { start_session }
it 'click and hold' do
driver . get 'https://www.selenium.dev/selenium/web/mouse_interaction.html'
clickable = driver . find_element ( id : 'clickable' )
driver . action
. click_and_hold ( clickable )
. perform
expect ( driver . find_element ( id : 'click-status' ) . text ) . to eq 'focused'
end
it 'click and release' do
driver . get 'https://www.selenium.dev/selenium/web/mouse_interaction.html'
clickable = driver . find_element ( id : 'click' )
driver . action
. click ( clickable )
. perform
expect ( driver . current_url ) . to include 'resultPage.html'
end
describe 'alternate button clicks' do
it 'right click' do
driver . get 'https://www.selenium.dev/selenium/web/mouse_interaction.html'
clickable = driver . find_element ( id : 'clickable' )
driver . action
. context_click ( clickable )
. perform
expect ( driver . find_element ( id : 'click-status' ) . text ) . to eq 'context-clicked'
end
it 'back click' do
driver . get 'https://www.selenium.dev/selenium/web/mouse_interaction.html'
driver . find_element ( id : 'click' ) . click
expect ( driver . title ) . to eq ( 'We Arrive Here' )
driver . action
. pointer_down ( :back )
. pointer_up ( :back )
. perform
expect ( driver . title ) . to eq ( 'BasicMouseInterfaceTest' )
end
it 'forward click' do
driver . get 'https://www.selenium.dev/selenium/web/mouse_interaction.html'
driver . find_element ( id : 'click' ) . click
driver . navigate . back
expect ( driver . title ) . to eq ( 'BasicMouseInterfaceTest' )
driver . action
. pointer_down ( :forward )
. pointer_up ( :forward )
. perform
expect ( driver . title ) . to eq ( 'We Arrive Here' )
end
end
it 'double click' do
driver . get 'https://www.selenium.dev/selenium/web/mouse_interaction.html'
clickable = driver . find_element ( id : 'clickable' )
driver . action
. double_click ( clickable )
. perform
expect ( driver . find_element ( id : 'click-status' ) . text ) . to eq 'double-clicked'
end
it 'hovers' do
driver . get 'https://www.selenium.dev/selenium/web/mouse_interaction.html'
hoverable = driver . find_element ( id : 'hover' )
driver . action
. move_to ( hoverable )
. perform
expect ( driver . find_element ( id : 'move-status' ) . text ) . to eq 'hovered'
end
describe 'move by offset' do
it 'offset from element' do
driver . get 'https://www.selenium.dev/selenium/web/mouse_interaction.html'
driver . action . scroll_to ( driver . find_element ( id : 'bottom' )) . perform
mouse_tracker = driver . find_element ( id : 'mouse-tracker' )
driver . action
. move_to ( mouse_tracker , 8 , 11 )
. perform
rect = mouse_tracker . rect
center_x = rect . width / 2
center_y = rect . height / 2
x_coord , y_coord = driver . find_element ( id : 'relative-location' ) . text . split ( ',' ) . map ( & :to_i )
expect ( x_coord ) . to be_within ( 1 ) . of ( center_x + 8 )
expect ( y_coord ) . to be_within ( 1 ) . of ( center_y + 11 )
end
it 'offset from viewport' do
driver . get 'https://www.selenium.dev/selenium/web/mouse_interaction.html'
driver . action
. move_to_location ( 8 , 12 )
. perform
x_coord , y_coord = driver . find_element ( id : 'absolute-location' ) . text . split ( ',' ) . map ( & :to_i )
expect ( x_coord ) . to be_within ( 1 ) . of ( 8 )
expect ( y_coord ) . to be_within ( 1 ) . of ( 12 )
end
it 'offset from current pointer location' do
driver . get 'https://www.selenium.dev/selenium/web/mouse_interaction.html'
driver . action . move_to_location ( 8 , 11 ) . perform
driver . action
. move_by ( 13 , 15 )
. perform
x_coord , y_coord = driver . find_element ( id : 'absolute-location' ) . text . split ( ',' ) . map ( & :to_i )
expect ( x_coord ) . to be_within ( 1 ) . of ( 8 + 13 )
expect ( y_coord ) . to be_within ( 1 ) . of ( 11 + 15 )
end
end
it 'drags to another element' do
driver . get 'https://www.selenium.dev/selenium/web/mouse_interaction.html'
draggable = driver . find_element ( id : 'draggable' )
droppable = driver . find_element ( id : 'droppable' )
driver . action
. drag_and_drop ( draggable , droppable )
. perform
expect ( driver . find_element ( id : 'drop-status' ) . text ) . to include ( 'dropped' )
end
it 'drags by an offset' do
driver . get 'https://www.selenium.dev/selenium/web/mouse_interaction.html'
draggable = driver . find_element ( id : 'draggable' )
start = draggable . rect
finish = driver . find_element ( id : 'droppable' ) . rect
driver . action
. drag_and_drop_by ( draggable , finish . x - start . x , finish . y - start . y )
. perform
expect ( driver . find_element ( id : 'drop-status' ) . text ) . to include ( 'dropped' )
end
end
Selenium v4.5.0
const actions = driver . actions ({ async : true });
await actions . press ( Button . BACK ). release ( Button . BACK ). perform ()
Show full example const { By , Button , Browser , Builder } = require ( 'selenium-webdriver' );
const assert = require ( 'assert' );
describe ( 'Should be able to perform BACK click and FORWARD click' , function () {
let driver ;
before ( async function () {
driver = new Builder (). forBrowser ( 'chrome' ). build ();
});
after ( async () => await driver . quit ());
it ( 'Back click' , async function () {
await driver . get ( 'https://selenium.dev/selenium/web/mouse_interaction.html' );
await driver . findElement ( By . id ( "click" )). click ();
assert . deepStrictEqual ( await driver . getTitle (), `We Arrive Here` )
const actions = driver . actions ({ async : true });
await actions . press ( Button . BACK ). release ( Button . BACK ). perform ()
assert . deepStrictEqual ( await driver . getTitle (), `BasicMouseInterfaceTest` )
});
it ( 'Forward click' , async function () {
await driver . get ( 'https://selenium.dev/selenium/web/mouse_interaction.html' );
await driver . findElement ( By . id ( "click" )). click ();
await driver . navigate (). back ();
assert . deepStrictEqual ( await driver . getTitle (), `BasicMouseInterfaceTest` )
const actions = driver . actions ({ async : true });
await actions . press ( Button . FORWARD ). release ( Button . FORWARD ). perform ()
assert . deepStrictEqual ( await driver . getTitle (), `We Arrive Here` )
});
});
val mouse = PointerInput ( PointerInput . Kind . MOUSE , "default mouse" )
val actions = Sequence ( mouse , 0 )
. addAction ( mouse . createPointerDown ( PointerInput . MouseButton . BACK . asArg ()))
. addAction ( mouse . createPointerUp ( PointerInput . MouseButton . BACK . asArg ()))
( driver as RemoteWebDriver ). perform ( Collections . singletonList ( actions ))
Show full example 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.Rectangle
import org.openqa.selenium.WebElement
import org.openqa.selenium.interactions.Actions
import org.openqa.selenium.interactions.PointerInput
import org.openqa.selenium.interactions.Sequence
import org.openqa.selenium.remote.RemoteWebDriver
import java.time.Duration
import java.util.Collections
class MouseTest : BaseTest () {
@Test
fun clickAndHold () {
driver . get ( "https://www.selenium.dev/selenium/web/mouse_interaction.html" )
val clickable = driver . findElement ( By . id ( "clickable" ))
Actions ( driver )
. clickAndHold ( clickable )
. perform ()
Assertions . assertEquals ( "focused" , driver . findElement ( By . id ( "click-status" )). getText ())
}
@Test
fun clickAndRelease () {
driver . get ( "https://www.selenium.dev/selenium/web/mouse_interaction.html" )
val clickable = driver . findElement ( By . id ( "click" ))
Actions ( driver )
. click ( clickable )
. perform ()
Assertions . assertTrue ( driver . getCurrentUrl () !! . contains ( "resultPage.html" ))
}
@Test
fun rightClick () {
driver . get ( "https://www.selenium.dev/selenium/web/mouse_interaction.html" )
val clickable = driver . findElement ( By . id ( "clickable" ))
Actions ( driver )
. contextClick ( clickable )
. perform ()
Assertions . assertEquals ( "context-clicked" , driver . findElement ( By . id ( "click-status" )). getText ())
}
@Test
fun backClick () {
driver . get ( "https://www.selenium.dev/selenium/web/mouse_interaction.html" )
driver . findElement ( By . id ( "click" )). click ()
Assertions . assertEquals ( driver . getTitle (), "We Arrive Here" )
val mouse = PointerInput ( PointerInput . Kind . MOUSE , "default mouse" )
val actions = Sequence ( mouse , 0 )
. addAction ( mouse . createPointerDown ( PointerInput . MouseButton . BACK . asArg ()))
. addAction ( mouse . createPointerUp ( PointerInput . MouseButton . BACK . asArg ()))
( driver as RemoteWebDriver ). perform ( Collections . singletonList ( actions ))
Assertions . assertEquals ( "BasicMouseInterfaceTest" , driver . getTitle ())
}
@Test
fun forwardClick () {
driver . get ( "https://www.selenium.dev/selenium/web/mouse_interaction.html" )
driver . findElement ( By . id ( "click" )). click ()
driver . navigate (). back ()
Assertions . assertEquals ( driver . getTitle (), "BasicMouseInterfaceTest" )
val mouse = PointerInput ( PointerInput . Kind . MOUSE , "default mouse" )
val actions = Sequence ( mouse , 0 )
. addAction ( mouse . createPointerDown ( PointerInput . MouseButton . FORWARD . asArg ()))
. addAction ( mouse . createPointerUp ( PointerInput . MouseButton . FORWARD . asArg ()))
( driver as RemoteWebDriver ). perform ( Collections . singletonList ( actions ))
Assertions . assertEquals ( "We Arrive Here" , driver . getTitle ())
}
@Test
fun doubleClick () {
driver . get ( "https://www.selenium.dev/selenium/web/mouse_interaction.html" )
val clickable = driver . findElement ( By . id ( "clickable" ))
Actions ( driver )
. doubleClick ( clickable )
. perform ()
Assertions . assertEquals ( "double-clicked" , driver . findElement ( By . id ( "click-status" )). getText ())
}
@Test
fun hovers () {
driver . get ( "https://www.selenium.dev/selenium/web/mouse_interaction.html" )
val hoverable = driver . findElement ( By . id ( "hover" ))
Actions ( driver )
. moveToElement ( hoverable )
. perform ()
Assertions . assertEquals ( "hovered" , driver . findElement ( By . id ( "move-status" )). getText ())
}
@Test
fun moveByOffsetFromElement () {
driver . get ( "https://www.selenium.dev/selenium/web/mouse_interaction.html" )
driver . manage (). window (). fullscreen ()
val tracker = driver . findElement ( By . id ( "mouse-tracker" ))
Actions ( driver )
. moveToElement ( tracker , 8 , 0 )
. perform ()
val result = driver . findElement ( By . id ( "relative-location" )). getText (). split ( ", " )
Assertions . assertTrue ( Math . abs ( Integer . parseInt ( result [ 0 ]) - 100 - 8 ) < 2 )
}
@Test
fun moveByOffsetFromViewport () {
driver . get ( "https://www.selenium.dev/selenium/web/mouse_interaction.html" )
val mouse = PointerInput ( PointerInput . Kind . MOUSE , "default mouse" )
val actions = Sequence ( mouse , 0 )
. addAction ( mouse . createPointerMove ( Duration . ZERO , PointerInput . Origin . viewport (), 8 , 12 ))
( driver as RemoteWebDriver ). perform ( Collections . singletonList ( actions ))
val result = driver . findElement ( By . id ( "absolute-location" )). getText (). split ( ", " )
Assertions . assertTrue ( Math . abs ( Integer . parseInt ( result [ 0 ]) - 8 ) < 2 )
Assertions . assertTrue ( Math . abs ( Integer . parseInt ( result [ 1 ]) - 12 ) < 2 )
}
@Test
fun moveByOffsetFromCurrentPointer () {
driver . get ( "https://www.selenium.dev/selenium/web/mouse_interaction.html" )
val mouse = PointerInput ( PointerInput . Kind . MOUSE , "default mouse" )
val actions = Sequence ( mouse , 0 )
. addAction ( mouse . createPointerMove ( Duration . ZERO , PointerInput . Origin . viewport (), 8 , 11 ))
( driver as RemoteWebDriver ). perform ( Collections . singletonList ( actions ))
Actions ( driver )
. moveByOffset ( 13 , 15 )
. perform ()
val result = driver . findElement ( By . id ( "absolute-location" )). getText (). split ( ", " )
Assertions . assertTrue ( Math . abs ( Integer . parseInt ( result [ 0 ]) - 8 - 13 ) < 2 )
Assertions . assertTrue ( Math . abs ( Integer . parseInt ( result [ 1 ]) - 11 - 15 ) < 2 )
}
@Test
fun dragsToElement () {
driver . get ( "https://www.selenium.dev/selenium/web/mouse_interaction.html" )
val draggable = driver . findElement ( By . id ( "draggable" ))
val droppable = driver . findElement ( By . id ( "droppable" ))
Actions ( driver )
. dragAndDrop ( draggable , droppable )
. perform ()
Assertions . assertEquals ( "dropped" , driver . findElement ( By . id ( "drop-status" )). getText ())
}
@Test
fun dragsByOffset () {
driver . get ( "https://www.selenium.dev/selenium/web/mouse_interaction.html" )
val draggable = driver . findElement ( By . id ( "draggable" ))
val start = draggable . getRect ()
val finish = driver . findElement ( By . id ( "droppable" )). getRect ()
Actions ( driver )
. dragAndDropBy ( draggable , finish . getX () - start . getX (), finish . getY () - start . getY ())
. perform ()
Assertions . assertEquals ( "dropped" , driver . findElement ( By . id ( "drop-status" )). getText ())
}
}
botão de avançar) do mouse Este termo se refere a um clique com o botão X2 (botão de avançar) do mouse. Não existe um método de conveniência específico para essa ação, sendo apenas a pressão e liberação do botão do mouse de número 4.
Java
Python
CSharp
Ruby
JavaScript
Kotlin PointerInput mouse = new PointerInput ( PointerInput . Kind . MOUSE , "default mouse" );
Sequence actions = new Sequence ( mouse , 0 )
. addAction ( mouse . createPointerDown ( PointerInput . MouseButton . FORWARD . asArg ()))
. addAction ( mouse . createPointerUp ( PointerInput . MouseButton . FORWARD . asArg ()));
(( RemoteWebDriver ) driver ). perform ( Collections . singletonList ( actions ));
Show full example 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.Rectangle ;
import org.openqa.selenium.WebElement ;
import org.openqa.selenium.interactions.Actions ;
import org.openqa.selenium.interactions.PointerInput ;
import org.openqa.selenium.interactions.Sequence ;
import org.openqa.selenium.remote.RemoteWebDriver ;
import java.time.Duration ;
import java.util.Collections ;
public class MouseTest extends BaseChromeTest {
@Test
public void clickAndHold () {
driver . get ( "https://www.selenium.dev/selenium/web/mouse_interaction.html" );
WebElement clickable = driver . findElement ( By . id ( "clickable" ));
new Actions ( driver )
. clickAndHold ( clickable )
. perform ();
Assertions . assertEquals ( "focused" , driver . findElement ( By . id ( "click-status" )). getText ());
}
@Test
public void clickAndRelease () {
driver . get ( "https://www.selenium.dev/selenium/web/mouse_interaction.html" );
WebElement clickable = driver . findElement ( By . id ( "click" ));
new Actions ( driver )
. click ( clickable )
. perform ();
Assertions . assertTrue ( driver . getCurrentUrl (). contains ( "resultPage.html" ));
}
@Test
public void rightClick () {
driver . get ( "https://www.selenium.dev/selenium/web/mouse_interaction.html" );
WebElement clickable = driver . findElement ( By . id ( "clickable" ));
new Actions ( driver )
. contextClick ( clickable )
. perform ();
Assertions . assertEquals ( "context-clicked" , driver . findElement ( By . id ( "click-status" )). getText ());
}
@Test
public void backClick () {
driver . get ( "https://www.selenium.dev/selenium/web/mouse_interaction.html" );
driver . findElement ( By . id ( "click" )). click ();
Assertions . assertEquals ( driver . getTitle (), "We Arrive Here" );
PointerInput mouse = new PointerInput ( PointerInput . Kind . MOUSE , "default mouse" );
Sequence actions = new Sequence ( mouse , 0 )
. addAction ( mouse . createPointerDown ( PointerInput . MouseButton . BACK . asArg ()))
. addAction ( mouse . createPointerUp ( PointerInput . MouseButton . BACK . asArg ()));
(( RemoteWebDriver ) driver ). perform ( Collections . singletonList ( actions ));
Assertions . assertEquals ( "BasicMouseInterfaceTest" , driver . getTitle ());
}
@Test
public void forwardClick () {
driver . get ( "https://www.selenium.dev/selenium/web/mouse_interaction.html" );
driver . findElement ( By . id ( "click" )). click ();
driver . navigate (). back ();
Assertions . assertEquals ( driver . getTitle (), "BasicMouseInterfaceTest" );
PointerInput mouse = new PointerInput ( PointerInput . Kind . MOUSE , "default mouse" );
Sequence actions = new Sequence ( mouse , 0 )
. addAction ( mouse . createPointerDown ( PointerInput . MouseButton . FORWARD . asArg ()))
. addAction ( mouse . createPointerUp ( PointerInput . MouseButton . FORWARD . asArg ()));
(( RemoteWebDriver ) driver ). perform ( Collections . singletonList ( actions ));
Assertions . assertEquals ( "We Arrive Here" , driver . getTitle ());
}
@Test
public void doubleClick () {
driver . get ( "https://www.selenium.dev/selenium/web/mouse_interaction.html" );
WebElement clickable = driver . findElement ( By . id ( "clickable" ));
new Actions ( driver )
. doubleClick ( clickable )
. perform ();
Assertions . assertEquals ( "double-clicked" , driver . findElement ( By . id ( "click-status" )). getText ());
}
@Test
public void hovers () {
driver . get ( "https://www.selenium.dev/selenium/web/mouse_interaction.html" );
WebElement hoverable = driver . findElement ( By . id ( "hover" ));
new Actions ( driver )
. moveToElement ( hoverable )
. perform ();
Assertions . assertEquals ( "hovered" , driver . findElement ( By . id ( "move-status" )). getText ());
}
@Test
public void moveByOffsetFromElement () {
driver . get ( "https://www.selenium.dev/selenium/web/mouse_interaction.html" );
driver . manage (). window (). fullscreen ();
WebElement tracker = driver . findElement ( By . id ( "mouse-tracker" ));
new Actions ( driver )
. moveToElement ( tracker , 8 , 0 )
. perform ();
String [] result = driver . findElement ( By . id ( "relative-location" )). getText (). split ( ", " );
Assertions . assertTrue ( Math . abs ( Integer . parseInt ( result [ 0 ] ) - 100 - 8 ) < 2 );
}
@Test
public void moveByOffsetFromViewport () {
driver . get ( "https://www.selenium.dev/selenium/web/mouse_interaction.html" );
PointerInput mouse = new PointerInput ( PointerInput . Kind . MOUSE , "default mouse" );
Sequence actions = new Sequence ( mouse , 0 )
. addAction ( mouse . createPointerMove ( Duration . ZERO , PointerInput . Origin . viewport (), 8 , 12 ));
(( RemoteWebDriver ) driver ). perform ( Collections . singletonList ( actions ));
String [] result = driver . findElement ( By . id ( "absolute-location" )). getText (). split ( ", " );
Assertions . assertTrue ( Math . abs ( Integer . parseInt ( result [ 0 ] ) - 8 ) < 2 );
Assertions . assertTrue ( Math . abs ( Integer . parseInt ( result [ 1 ] ) - 12 ) < 2 );
}
@Test
public void moveByOffsetFromCurrentPointer () {
driver . get ( "https://www.selenium.dev/selenium/web/mouse_interaction.html" );
PointerInput mouse = new PointerInput ( PointerInput . Kind . MOUSE , "default mouse" );
Sequence actions = new Sequence ( mouse , 0 )
. addAction ( mouse . createPointerMove ( Duration . ZERO , PointerInput . Origin . viewport (), 8 , 11 ));
(( RemoteWebDriver ) driver ). perform ( Collections . singletonList ( actions ));
new Actions ( driver )
. moveByOffset ( 13 , 15 )
. perform ();
String [] result = driver . findElement ( By . id ( "absolute-location" )). getText (). split ( ", " );
Assertions . assertTrue ( Math . abs ( Integer . parseInt ( result [ 0 ] ) - 8 - 13 ) < 2 );
Assertions . assertTrue ( Math . abs ( Integer . parseInt ( result [ 1 ] ) - 11 - 15 ) < 2 );
}
@Test
public void dragsToElement () {
driver . get ( "https://www.selenium.dev/selenium/web/mouse_interaction.html" );
WebElement draggable = driver . findElement ( By . id ( "draggable" ));
WebElement droppable = driver . findElement ( By . id ( "droppable" ));
new Actions ( driver )
. dragAndDrop ( draggable , droppable )
. perform ();
Assertions . assertEquals ( "dropped" , driver . findElement ( By . id ( "drop-status" )). getText ());
}
@Test
public void dragsByOffset () {
driver . get ( "https://www.selenium.dev/selenium/web/mouse_interaction.html" );
WebElement draggable = driver . findElement ( By . id ( "draggable" ));
Rectangle start = draggable . getRect ();
Rectangle finish = driver . findElement ( By . id ( "droppable" )). getRect ();
new Actions ( driver )
. dragAndDropBy ( draggable , finish . getX () - start . getX (), finish . getY () - start . getY ())
. perform ();
Assertions . assertEquals ( "dropped" , driver . findElement ( By . id ( "drop-status" )). getText ());
}
}
Selenium v4.2
action = ActionBuilder ( driver )
action . pointer_action . pointer_down ( MouseButton . FORWARD )
action . pointer_action . pointer_up ( MouseButton . FORWARD )
action . perform ()
Show full example import pytest
from time import sleep
from selenium.webdriver import ActionChains
from selenium.webdriver.common.actions.action_builder import ActionBuilder
from selenium.webdriver.common.actions.mouse_button import MouseButton
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
def test_click_and_hold ( driver ):
driver . get ( 'https://selenium.dev/selenium/web/mouse_interaction.html' )
clickable = driver . find_element ( By . ID , "clickable" )
ActionChains ( driver ) \
. click_and_hold ( clickable ) \
. perform ()
sleep ( 0.5 )
assert driver . find_element ( By . ID , "click-status" ) . text == "focused"
def test_click_and_release ( driver ):
driver . get ( 'https://selenium.dev/selenium/web/mouse_interaction.html' )
clickable = driver . find_element ( By . ID , "click" )
ActionChains ( driver ) \
. click ( clickable ) \
. perform ()
assert "resultPage.html" in driver . current_url
def test_right_click ( driver ):
driver . get ( 'https://selenium.dev/selenium/web/mouse_interaction.html' )
clickable = driver . find_element ( By . ID , "clickable" )
ActionChains ( driver ) \
. context_click ( clickable ) \
. perform ()
sleep ( 0.5 )
assert driver . find_element ( By . ID , "click-status" ) . text == "context-clicked"
def test_back_click_ab ( driver ):
driver . get ( 'https://selenium.dev/selenium/web/mouse_interaction.html' )
driver . find_element ( By . ID , "click" ) . click ()
assert driver . title == "We Arrive Here"
action = ActionBuilder ( driver )
action . pointer_action . pointer_down ( MouseButton . BACK )
action . pointer_action . pointer_up ( MouseButton . BACK )
action . perform ()
assert driver . title == "BasicMouseInterfaceTest"
def test_forward_click_ab ( driver ):
driver . get ( 'https://selenium.dev/selenium/web/mouse_interaction.html' )
driver . find_element ( By . ID , "click" ) . click ()
driver . back ()
assert driver . title == "BasicMouseInterfaceTest"
action = ActionBuilder ( driver )
action . pointer_action . pointer_down ( MouseButton . FORWARD )
action . pointer_action . pointer_up ( MouseButton . FORWARD )
action . perform ()
assert driver . title == "We Arrive Here"
def test_double_click ( driver ):
driver . get ( 'https://selenium.dev/selenium/web/mouse_interaction.html' )
clickable = driver . find_element ( By . ID , "clickable" )
ActionChains ( driver ) \
. double_click ( clickable ) \
. perform ()
assert driver . find_element ( By . ID , "click-status" ) . text == "double-clicked"
def test_hover ( driver ):
driver . get ( 'https://selenium.dev/selenium/web/mouse_interaction.html' )
hoverable = driver . find_element ( By . ID , "hover" )
ActionChains ( driver ) \
. move_to_element ( hoverable ) \
. perform ()
assert driver . find_element ( By . ID , "move-status" ) . text == "hovered"
def test_move_by_offset_from_element ( driver ):
driver . get ( 'https://selenium.dev/selenium/web/mouse_interaction.html' )
mouse_tracker = driver . find_element ( By . ID , "mouse-tracker" )
ActionChains ( driver ) \
. move_to_element_with_offset ( mouse_tracker , 8 , 0 ) \
. perform ()
coordinates = driver . find_element ( By . ID , "relative-location" ) . text . split ( ", " )
assert abs ( int ( coordinates [ 0 ]) - 100 - 8 ) < 2
def test_move_by_offset_from_viewport_origin_ab ( driver ):
driver . get ( 'https://selenium.dev/selenium/web/mouse_interaction.html' )
WebDriverWait ( driver , 10 ) . until ( EC . presence_of_element_located (( By . ID , "absolute-location" )))
action = ActionBuilder ( driver )
action . pointer_action . move_to_location ( 8 , 0 )
action . perform ()
coordinates = driver . find_element ( By . ID , "absolute-location" ) . text . split ( ", " )
assert abs ( int ( coordinates [ 0 ]) - 8 ) < 2
def test_move_by_offset_from_current_pointer_ab ( driver ):
driver . get ( 'https://selenium.dev/selenium/web/mouse_interaction.html' )
action = ActionBuilder ( driver )
action . pointer_action . move_to_location ( 6 , 3 )
action . perform ()
ActionChains ( driver ) \
. move_by_offset ( 13 , 15 ) \
. perform ()
coordinates = driver . find_element ( By . ID , "absolute-location" ) . text . split ( ", " )
assert abs ( int ( coordinates [ 0 ]) - 6 - 13 ) < 2
assert abs ( int ( coordinates [ 1 ]) - 3 - 15 ) < 2
def test_drag_and_drop_onto_element ( driver ):
driver . get ( 'https://selenium.dev/selenium/web/mouse_interaction.html' )
draggable = driver . find_element ( By . ID , "draggable" )
droppable = driver . find_element ( By . ID , "droppable" )
ActionChains ( driver ) \
. drag_and_drop ( draggable , droppable ) \
. perform ()
assert driver . find_element ( By . ID , "drop-status" ) . text == "dropped"
def test_drag_and_drop_by_offset ( driver ):
driver . get ( 'https://selenium.dev/selenium/web/mouse_interaction.html' )
draggable = driver . find_element ( By . ID , "draggable" )
start = draggable . location
finish = driver . find_element ( By . ID , "droppable" ) . location
ActionChains ( driver ) \
. drag_and_drop_by_offset ( draggable , finish [ 'x' ] - start [ 'x' ], finish [ 'y' ] - start [ 'y' ]) \
. perform ()
assert driver . find_element ( By . ID , "drop-status" ) . text == "dropped"
Selenium v4.2
ActionBuilder actionBuilder = new ActionBuilder ();
PointerInputDevice mouse = new PointerInputDevice ( PointerKind . Mouse , "default mouse" );
actionBuilder . AddAction ( mouse . CreatePointerDown ( MouseButton . Forward ));
actionBuilder . AddAction ( mouse . CreatePointerUp ( MouseButton . Forward ));
(( IActionExecutor ) driver ). PerformActions ( actionBuilder . ToActionSequenceList ());
Show full example using System ;
using System.Drawing ;
using Microsoft.VisualStudio.TestTools.UnitTesting ;
using OpenQA.Selenium ;
using OpenQA.Selenium.Interactions ;
namespace SeleniumDocs.ActionsAPI
{
[TestClass]
public class MouseTest : BaseChromeTest
{
[TestMethod]
public void ClickAndHold ()
{
driver . Url = "https://selenium.dev/selenium/web/mouse_interaction.html" ;
IWebElement clickable = driver . FindElement ( By . Id ( "clickable" ));
new Actions ( driver )
. ClickAndHold ( clickable )
. Perform ();
Assert . AreEqual ( "focused" , driver . FindElement ( By . Id ( "click-status" )). Text );
}
[TestMethod]
public void ClickAndRelease ()
{
driver . Url = "https://selenium.dev/selenium/web/mouse_interaction.html" ;
IWebElement clickable = driver . FindElement ( By . Id ( "click" ));
new Actions ( driver )
. Click ( clickable )
. Perform ();
Assert . IsTrue ( driver . Url . Contains ( "resultPage.html" ));
}
[TestMethod]
public void RightClick ()
{
driver . Url = "https://selenium.dev/selenium/web/mouse_interaction.html" ;
IWebElement clickable = driver . FindElement ( By . Id ( "clickable" ));
new Actions ( driver )
. ContextClick ( clickable )
. Perform ();
Assert . AreEqual ( "context-clicked" , driver . FindElement ( By . Id ( "click-status" )). Text );
}
[TestMethod]
public void BackClick ()
{
driver . Url = "https://selenium.dev/selenium/web/mouse_interaction.html" ;
driver . FindElement ( By . Id ( "click" )). Click ();
Assert . AreEqual ( "We Arrive Here" , driver . Title );
ActionBuilder actionBuilder = new ActionBuilder ();
PointerInputDevice mouse = new PointerInputDevice ( PointerKind . Mouse , "default mouse" );
actionBuilder . AddAction ( mouse . CreatePointerDown ( MouseButton . Back ));
actionBuilder . AddAction ( mouse . CreatePointerUp ( MouseButton . Back ));
(( IActionExecutor ) driver ). PerformActions ( actionBuilder . ToActionSequenceList ());
Assert . AreEqual ( "BasicMouseInterfaceTest" , driver . Title );
}
[TestMethod]
public void ForwardClick ()
{
driver . Url = "https://selenium.dev/selenium/web/mouse_interaction.html" ;
driver . FindElement ( By . Id ( "click" )). Click ();
driver . Navigate (). Back ();
Assert . AreEqual ( "BasicMouseInterfaceTest" , driver . Title );
ActionBuilder actionBuilder = new ActionBuilder ();
PointerInputDevice mouse = new PointerInputDevice ( PointerKind . Mouse , "default mouse" );
actionBuilder . AddAction ( mouse . CreatePointerDown ( MouseButton . Forward ));
actionBuilder . AddAction ( mouse . CreatePointerUp ( MouseButton . Forward ));
(( IActionExecutor ) driver ). PerformActions ( actionBuilder . ToActionSequenceList ());
Assert . AreEqual ( "We Arrive Here" , driver . Title );
}
[TestMethod]
public void DoubleClick ()
{
driver . Url = "https://selenium.dev/selenium/web/mouse_interaction.html" ;
IWebElement clickable = driver . FindElement ( By . Id ( "clickable" ));
new Actions ( driver )
. DoubleClick ( clickable )
. Perform ();
Assert . AreEqual ( "double-clicked" , driver . FindElement ( By . Id ( "click-status" )). Text );
}
[TestMethod]
public void Hovers ()
{
driver . Url = "https://selenium.dev/selenium/web/mouse_interaction.html" ;
IWebElement hoverable = driver . FindElement ( By . Id ( "hover" ));
new Actions ( driver )
. MoveToElement ( hoverable )
. Perform ();
Assert . AreEqual ( "hovered" , driver . FindElement ( By . Id ( "move-status" )). Text );
}
[TestMethod]
[Obsolete("Obsolete")]
public void MoveByOffsetFromTopLeftOfElement ()
{
driver . Url = "https://selenium.dev/selenium/web/mouse_interaction.html" ;
IWebElement tracker = driver . FindElement ( By . Id ( "mouse-tracker" ));
new Actions ( driver )
. MoveToElement ( tracker , 8 , 0 )
. Perform ();
string [] result = driver . FindElement ( By . Id ( "relative-location" )). Text . Split ( ", " );
Assert . IsTrue ( Math . Abs ( int . Parse ( result [ 0 ]) - 100 - 8 ) < 2 );
}
[TestMethod]
public void MoveByOffsetFromCenterOfElement ()
{
driver . Url = "https://selenium.dev/selenium/web/mouse_interaction.html" ;
IWebElement tracker = driver . FindElement ( By . Id ( "mouse-tracker" ));
new Actions ( driver )
. MoveToElement ( tracker , 8 , 0 )
. Perform ();
string [] result = driver . FindElement ( By . Id ( "relative-location" )). Text . Split ( ", " );
Assert . IsTrue ( Math . Abs ( int . Parse ( result [ 0 ]) - 100 - 8 ) < 2 );
}
[TestMethod]
public void MoveByOffsetFromViewport ()
{
driver . Url = "https://selenium.dev/selenium/web/mouse_interaction.html" ;
ActionBuilder actionBuilder = new ActionBuilder ();
PointerInputDevice mouse = new PointerInputDevice ( PointerKind . Mouse , "default mouse" );
actionBuilder . AddAction ( mouse . CreatePointerMove ( CoordinateOrigin . Viewport ,
8 , 0 , TimeSpan . Zero ));
(( IActionExecutor ) driver ). PerformActions ( actionBuilder . ToActionSequenceList ());
string [] result = driver . FindElement ( By . Id ( "absolute-location" )). Text . Split ( ", " );
Assert . IsTrue ( Math . Abs ( int . Parse ( result [ 0 ]) - 8 ) < 2 );
}
[TestMethod]
public void MoveByOffsetFromCurrentPointerLocation ()
{
driver . Url = "https://selenium.dev/selenium/web/mouse_interaction.html" ;
ActionBuilder actionBuilder = new ActionBuilder ();
PointerInputDevice mouse = new PointerInputDevice ( PointerKind . Mouse , "default mouse" );
actionBuilder . AddAction ( mouse . CreatePointerMove ( CoordinateOrigin . Viewport ,
8 , 12 , TimeSpan . Zero ));
(( IActionExecutor ) driver ). PerformActions ( actionBuilder . ToActionSequenceList ());
new Actions ( driver )
. MoveByOffset ( 13 , 15 )
. Perform ();
string [] result = driver . FindElement ( By . Id ( "absolute-location" )). Text . Split ( ", " );
Assert . IsTrue ( Math . Abs ( int . Parse ( result [ 0 ]) - 8 - 13 ) < 2 );
Assert . IsTrue ( Math . Abs ( int . Parse ( result [ 1 ]) - 12 - 15 ) < 2 );
}
[TestMethod]
public void DragToElement ()
{
driver . Url = "https://selenium.dev/selenium/web/mouse_interaction.html" ;
IWebElement draggable = driver . FindElement ( By . Id ( "draggable" ));
IWebElement droppable = driver . FindElement ( By . Id ( "droppable" ));
new Actions ( driver )
. DragAndDrop ( draggable , droppable )
. Perform ();
Assert . AreEqual ( "dropped" , driver . FindElement ( By . Id ( "drop-status" )). Text );
}
[TestMethod]
public void DragByOffset ()
{
driver . Url = "https://selenium.dev/selenium/web/mouse_interaction.html" ;
IWebElement draggable = driver . FindElement ( By . Id ( "draggable" ));
Point start = draggable . Location ;
Point finish = driver . FindElement ( By . Id ( "droppable" )). Location ;
new Actions ( driver )
. DragAndDropToOffset ( draggable , finish . X - start . X , finish . Y - start . Y )
. Perform ();
Assert . AreEqual ( "dropped" , driver . FindElement ( By . Id ( "drop-status" )). Text );
}
}
}
Selenium v4.2
driver . action
. pointer_down ( :forward )
. pointer_up ( :forward )
. perform
Show full example # frozen_string_literal: true
require 'spec_helper'
RSpec . describe 'Mouse' do
let ( :driver ) { start_session }
it 'click and hold' do
driver . get 'https://www.selenium.dev/selenium/web/mouse_interaction.html'
clickable = driver . find_element ( id : 'clickable' )
driver . action
. click_and_hold ( clickable )
. perform
expect ( driver . find_element ( id : 'click-status' ) . text ) . to eq 'focused'
end
it 'click and release' do
driver . get 'https://www.selenium.dev/selenium/web/mouse_interaction.html'
clickable = driver . find_element ( id : 'click' )
driver . action
. click ( clickable )
. perform
expect ( driver . current_url ) . to include 'resultPage.html'
end
describe 'alternate button clicks' do
it 'right click' do
driver . get 'https://www.selenium.dev/selenium/web/mouse_interaction.html'
clickable = driver . find_element ( id : 'clickable' )
driver . action
. context_click ( clickable )
. perform
expect ( driver . find_element ( id : 'click-status' ) . text ) . to eq 'context-clicked'
end
it 'back click' do
driver . get 'https://www.selenium.dev/selenium/web/mouse_interaction.html'
driver . find_element ( id : 'click' ) . click
expect ( driver . title ) . to eq ( 'We Arrive Here' )
driver . action
. pointer_down ( :back )
. pointer_up ( :back )
. perform
expect ( driver . title ) . to eq ( 'BasicMouseInterfaceTest' )
end
it 'forward click' do
driver . get 'https://www.selenium.dev/selenium/web/mouse_interaction.html'
driver . find_element ( id : 'click' ) . click
driver . navigate . back
expect ( driver . title ) . to eq ( 'BasicMouseInterfaceTest' )
driver . action
. pointer_down ( :forward )
. pointer_up ( :forward )
. perform
expect ( driver . title ) . to eq ( 'We Arrive Here' )
end
end
it 'double click' do
driver . get 'https://www.selenium.dev/selenium/web/mouse_interaction.html'
clickable = driver . find_element ( id : 'clickable' )
driver . action
. double_click ( clickable )
. perform
expect ( driver . find_element ( id : 'click-status' ) . text ) . to eq 'double-clicked'
end
it 'hovers' do
driver . get 'https://www.selenium.dev/selenium/web/mouse_interaction.html'
hoverable = driver . find_element ( id : 'hover' )
driver . action
. move_to ( hoverable )
. perform
expect ( driver . find_element ( id : 'move-status' ) . text ) . to eq 'hovered'
end
describe 'move by offset' do
it 'offset from element' do
driver . get 'https://www.selenium.dev/selenium/web/mouse_interaction.html'
driver . action . scroll_to ( driver . find_element ( id : 'bottom' )) . perform
mouse_tracker = driver . find_element ( id : 'mouse-tracker' )
driver . action
. move_to ( mouse_tracker , 8 , 11 )
. perform
rect = mouse_tracker . rect
center_x = rect . width / 2
center_y = rect . height / 2
x_coord , y_coord = driver . find_element ( id : 'relative-location' ) . text . split ( ',' ) . map ( & :to_i )
expect ( x_coord ) . to be_within ( 1 ) . of ( center_x + 8 )
expect ( y_coord ) . to be_within ( 1 ) . of ( center_y + 11 )
end
it 'offset from viewport' do
driver . get 'https://www.selenium.dev/selenium/web/mouse_interaction.html'
driver . action
. move_to_location ( 8 , 12 )
. perform
x_coord , y_coord = driver . find_element ( id : 'absolute-location' ) . text . split ( ',' ) . map ( & :to_i )
expect ( x_coord ) . to be_within ( 1 ) . of ( 8 )
expect ( y_coord ) . to be_within ( 1 ) . of ( 12 )
end
it 'offset from current pointer location' do
driver . get 'https://www.selenium.dev/selenium/web/mouse_interaction.html'
driver . action . move_to_location ( 8 , 11 ) . perform
driver . action
. move_by ( 13 , 15 )
. perform
x_coord , y_coord = driver . find_element ( id : 'absolute-location' ) . text . split ( ',' ) . map ( & :to_i )
expect ( x_coord ) . to be_within ( 1 ) . of ( 8 + 13 )
expect ( y_coord ) . to be_within ( 1 ) . of ( 11 + 15 )
end
end
it 'drags to another element' do
driver . get 'https://www.selenium.dev/selenium/web/mouse_interaction.html'
draggable = driver . find_element ( id : 'draggable' )
droppable = driver . find_element ( id : 'droppable' )
driver . action
. drag_and_drop ( draggable , droppable )
. perform
expect ( driver . find_element ( id : 'drop-status' ) . text ) . to include ( 'dropped' )
end
it 'drags by an offset' do
driver . get 'https://www.selenium.dev/selenium/web/mouse_interaction.html'
draggable = driver . find_element ( id : 'draggable' )
start = draggable . rect
finish = driver . find_element ( id : 'droppable' ) . rect
driver . action
. drag_and_drop_by ( draggable , finish . x - start . x , finish . y - start . y )
. perform
expect ( driver . find_element ( id : 'drop-status' ) . text ) . to include ( 'dropped' )
end
end
Selenium v4.5.0
const actions = driver . actions ({ async : true });
await actions . press ( Button . FORWARD ). release ( Button . FORWARD ). perform ()
Show full example const { By , Button , Browser , Builder } = require ( 'selenium-webdriver' );
const assert = require ( 'assert' );
describe ( 'Should be able to perform BACK click and FORWARD click' , function () {
let driver ;
before ( async function () {
driver = new Builder (). forBrowser ( 'chrome' ). build ();
});
after ( async () => await driver . quit ());
it ( 'Back click' , async function () {
await driver . get ( 'https://selenium.dev/selenium/web/mouse_interaction.html' );
await driver . findElement ( By . id ( "click" )). click ();
assert . deepStrictEqual ( await driver . getTitle (), `We Arrive Here` )
const actions = driver . actions ({ async : true });
await actions . press ( Button . BACK ). release ( Button . BACK ). perform ()
assert . deepStrictEqual ( await driver . getTitle (), `BasicMouseInterfaceTest` )
});
it ( 'Forward click' , async function () {
await driver . get ( 'https://selenium.dev/selenium/web/mouse_interaction.html' );
await driver . findElement ( By . id ( "click" )). click ();
await driver . navigate (). back ();
assert . deepStrictEqual ( await driver . getTitle (), `BasicMouseInterfaceTest` )
const actions = driver . actions ({ async : true });
await actions . press ( Button . FORWARD ). release ( Button . FORWARD ). perform ()
assert . deepStrictEqual ( await driver . getTitle (), `We Arrive Here` )
});
});
val mouse = PointerInput ( PointerInput . Kind . MOUSE , "default mouse" )
val actions = Sequence ( mouse , 0 )
. addAction ( mouse . createPointerDown ( PointerInput . MouseButton . FORWARD . asArg ()))
. addAction ( mouse . createPointerUp ( PointerInput . MouseButton . FORWARD . asArg ()))
( driver as RemoteWebDriver ). perform ( Collections . singletonList ( actions ))
Show full example 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.Rectangle
import org.openqa.selenium.WebElement
import org.openqa.selenium.interactions.Actions
import org.openqa.selenium.interactions.PointerInput
import org.openqa.selenium.interactions.Sequence
import org.openqa.selenium.remote.RemoteWebDriver
import java.time.Duration
import java.util.Collections
class MouseTest : BaseTest () {
@Test
fun clickAndHold () {
driver . get ( "https://www.selenium.dev/selenium/web/mouse_interaction.html" )
val clickable = driver . findElement ( By . id ( "clickable" ))
Actions ( driver )
. clickAndHold ( clickable )
. perform ()
Assertions . assertEquals ( "focused" , driver . findElement ( By . id ( "click-status" )). getText ())
}
@Test
fun clickAndRelease () {
driver . get ( "https://www.selenium.dev/selenium/web/mouse_interaction.html" )
val clickable = driver . findElement ( By . id ( "click" ))
Actions ( driver )
. click ( clickable )
. perform ()
Assertions . assertTrue ( driver . getCurrentUrl () !! . contains ( "resultPage.html" ))
}
@Test
fun rightClick () {
driver . get ( "https://www.selenium.dev/selenium/web/mouse_interaction.html" )
val clickable = driver . findElement ( By . id ( "clickable" ))
Actions ( driver )
. contextClick ( clickable )
. perform ()
Assertions . assertEquals ( "context-clicked" , driver . findElement ( By . id ( "click-status" )). getText ())
}
@Test
fun backClick () {
driver . get ( "https://www.selenium.dev/selenium/web/mouse_interaction.html" )
driver . findElement ( By . id ( "click" )). click ()
Assertions . assertEquals ( driver . getTitle (), "We Arrive Here" )
val mouse = PointerInput ( PointerInput . Kind . MOUSE , "default mouse" )
val actions = Sequence ( mouse , 0 )
. addAction ( mouse . createPointerDown ( PointerInput . MouseButton . BACK . asArg ()))
. addAction ( mouse . createPointerUp ( PointerInput . MouseButton . BACK . asArg ()))
( driver as RemoteWebDriver ). perform ( Collections . singletonList ( actions ))
Assertions . assertEquals ( "BasicMouseInterfaceTest" , driver . getTitle ())
}
@Test
fun forwardClick () {
driver . get ( "https://www.selenium.dev/selenium/web/mouse_interaction.html" )
driver . findElement ( By . id ( "click" )). click ()
driver . navigate (). back ()
Assertions . assertEquals ( driver . getTitle (), "BasicMouseInterfaceTest" )
val mouse = PointerInput ( PointerInput . Kind . MOUSE , "default mouse" )
val actions = Sequence ( mouse , 0 )
. addAction ( mouse . createPointerDown ( PointerInput . MouseButton . FORWARD . asArg ()))
. addAction ( mouse . createPointerUp ( PointerInput . MouseButton . FORWARD . asArg ()))
( driver as RemoteWebDriver ). perform ( Collections . singletonList ( actions ))
Assertions . assertEquals ( "We Arrive Here" , driver . getTitle ())
}
@Test
fun doubleClick () {
driver . get ( "https://www.selenium.dev/selenium/web/mouse_interaction.html" )
val clickable = driver . findElement ( By . id ( "clickable" ))
Actions ( driver )
. doubleClick ( clickable )
. perform ()
Assertions . assertEquals ( "double-clicked" , driver . findElement ( By . id ( "click-status" )). getText ())
}
@Test
fun hovers () {
driver . get ( "https://www.selenium.dev/selenium/web/mouse_interaction.html" )
val hoverable = driver . findElement ( By . id ( "hover" ))
Actions ( driver )
. moveToElement ( hoverable )
. perform ()
Assertions . assertEquals ( "hovered" , driver . findElement ( By . id ( "move-status" )). getText ())
}
@Test
fun moveByOffsetFromElement () {
driver . get ( "https://www.selenium.dev/selenium/web/mouse_interaction.html" )
driver . manage (). window (). fullscreen ()
val tracker = driver . findElement ( By . id ( "mouse-tracker" ))
Actions ( driver )
. moveToElement ( tracker , 8 , 0 )
. perform ()
val result = driver . findElement ( By . id ( "relative-location" )). getText (). split ( ", " )
Assertions . assertTrue ( Math . abs ( Integer . parseInt ( result [ 0 ]) - 100 - 8 ) < 2 )
}
@Test
fun moveByOffsetFromViewport () {
driver . get ( "https://www.selenium.dev/selenium/web/mouse_interaction.html" )
val mouse = PointerInput ( PointerInput . Kind . MOUSE , "default mouse" )
val actions = Sequence ( mouse , 0 )
. addAction ( mouse . createPointerMove ( Duration . ZERO , PointerInput . Origin . viewport (), 8 , 12 ))
( driver as RemoteWebDriver ). perform ( Collections . singletonList ( actions ))
val result = driver . findElement ( By . id ( "absolute-location" )). getText (). split ( ", " )
Assertions . assertTrue ( Math . abs ( Integer . parseInt ( result [ 0 ]) - 8 ) < 2 )
Assertions . assertTrue ( Math . abs ( Integer . parseInt ( result [ 1 ]) - 12 ) < 2 )
}
@Test
fun moveByOffsetFromCurrentPointer () {
driver . get ( "https://www.selenium.dev/selenium/web/mouse_interaction.html" )
val mouse = PointerInput ( PointerInput . Kind . MOUSE , "default mouse" )
val actions = Sequence ( mouse , 0 )
. addAction ( mouse . createPointerMove ( Duration . ZERO , PointerInput . Origin . viewport (), 8 , 11 ))
( driver as RemoteWebDriver ). perform ( Collections . singletonList ( actions ))
Actions ( driver )
. moveByOffset ( 13 , 15 )
. perform ()
val result = driver . findElement ( By . id ( "absolute-location" )). getText (). split ( ", " )
Assertions . assertTrue ( Math . abs ( Integer . parseInt ( result [ 0 ]) - 8 - 13 ) < 2 )
Assertions . assertTrue ( Math . abs ( Integer . parseInt ( result [ 1 ]) - 11 - 15 ) < 2 )
}
@Test
fun dragsToElement () {
driver . get ( "https://www.selenium.dev/selenium/web/mouse_interaction.html" )
val draggable = driver . findElement ( By . id ( "draggable" ))
val droppable = driver . findElement ( By . id ( "droppable" ))
Actions ( driver )
. dragAndDrop ( draggable , droppable )
. perform ()
Assertions . assertEquals ( "dropped" , driver . findElement ( By . id ( "drop-status" )). getText ())
}
@Test
fun dragsByOffset () {
driver . get ( "https://www.selenium.dev/selenium/web/mouse_interaction.html" )
val draggable = driver . findElement ( By . id ( "draggable" ))
val start = draggable . getRect ()
val finish = driver . findElement ( By . id ( "droppable" )). getRect ()
Actions ( driver )
. dragAndDropBy ( draggable , finish . getX () - start . getX (), finish . getY () - start . getY ())
. perform ()
Assertions . assertEquals ( "dropped" , driver . findElement ( By . id ( "drop-status" )). getText ())
}
}
Duplo click Este método combina mover o mouse para o centro de um elemento com a pressão e liberação do botão esquerdo do mouse duas vezes. Isso é conhecido como “duplo clique”.
Java
Python
CSharp
Ruby
JavaScript
Kotlin WebElement clickable = driver . findElement ( By . id ( "clickable" ));
new Actions ( driver )
. doubleClick ( clickable )
. perform ();
Show full example 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.Rectangle ;
import org.openqa.selenium.WebElement ;
import org.openqa.selenium.interactions.Actions ;
import org.openqa.selenium.interactions.PointerInput ;
import org.openqa.selenium.interactions.Sequence ;
import org.openqa.selenium.remote.RemoteWebDriver ;
import java.time.Duration ;
import java.util.Collections ;
public class MouseTest extends BaseChromeTest {
@Test
public void clickAndHold () {
driver . get ( "https://www.selenium.dev/selenium/web/mouse_interaction.html" );
WebElement clickable = driver . findElement ( By . id ( "clickable" ));
new Actions ( driver )
. clickAndHold ( clickable )
. perform ();
Assertions . assertEquals ( "focused" , driver . findElement ( By . id ( "click-status" )). getText ());
}
@Test
public void clickAndRelease () {
driver . get ( "https://www.selenium.dev/selenium/web/mouse_interaction.html" );
WebElement clickable = driver . findElement ( By . id ( "click" ));
new Actions ( driver )
. click ( clickable )
. perform ();
Assertions . assertTrue ( driver . getCurrentUrl (). contains ( "resultPage.html" ));
}
@Test
public void rightClick () {
driver . get ( "https://www.selenium.dev/selenium/web/mouse_interaction.html" );
WebElement clickable = driver . findElement ( By . id ( "clickable" ));
new Actions ( driver )
. contextClick ( clickable )
. perform ();
Assertions . assertEquals ( "context-clicked" , driver . findElement ( By . id ( "click-status" )). getText ());
}
@Test
public void backClick () {
driver . get ( "https://www.selenium.dev/selenium/web/mouse_interaction.html" );
driver . findElement ( By . id ( "click" )). click ();
Assertions . assertEquals ( driver . getTitle (), "We Arrive Here" );
PointerInput mouse = new PointerInput ( PointerInput . Kind . MOUSE , "default mouse" );
Sequence actions = new Sequence ( mouse , 0 )
. addAction ( mouse . createPointerDown ( PointerInput . MouseButton . BACK . asArg ()))
. addAction ( mouse . createPointerUp ( PointerInput . MouseButton . BACK . asArg ()));
(( RemoteWebDriver ) driver ). perform ( Collections . singletonList ( actions ));
Assertions . assertEquals ( "BasicMouseInterfaceTest" , driver . getTitle ());
}
@Test
public void forwardClick () {
driver . get ( "https://www.selenium.dev/selenium/web/mouse_interaction.html" );
driver . findElement ( By . id ( "click" )). click ();
driver . navigate (). back ();
Assertions . assertEquals ( driver . getTitle (), "BasicMouseInterfaceTest" );
PointerInput mouse = new PointerInput ( PointerInput . Kind . MOUSE , "default mouse" );
Sequence actions = new Sequence ( mouse , 0 )
. addAction ( mouse . createPointerDown ( PointerInput . MouseButton . FORWARD . asArg ()))
. addAction ( mouse . createPointerUp ( PointerInput . MouseButton . FORWARD . asArg ()));
(( RemoteWebDriver ) driver ). perform ( Collections . singletonList ( actions ));
Assertions . assertEquals ( "We Arrive Here" , driver . getTitle ());
}
@Test
public void doubleClick () {
driver . get ( "https://www.selenium.dev/selenium/web/mouse_interaction.html" );
WebElement clickable = driver . findElement ( By . id ( "clickable" ));
new Actions ( driver )
. doubleClick ( clickable )
. perform ();
Assertions . assertEquals ( "double-clicked" , driver . findElement ( By . id ( "click-status" )). getText ());
}
@Test
public void hovers () {
driver . get ( "https://www.selenium.dev/selenium/web/mouse_interaction.html" );
WebElement hoverable = driver . findElement ( By . id ( "hover" ));
new Actions ( driver )
. moveToElement ( hoverable )
. perform ();
Assertions . assertEquals ( "hovered" , driver . findElement ( By . id ( "move-status" )). getText ());
}
@Test
public void moveByOffsetFromElement () {
driver . get ( "https://www.selenium.dev/selenium/web/mouse_interaction.html" );
driver . manage (). window (). fullscreen ();
WebElement tracker = driver . findElement ( By . id ( "mouse-tracker" ));
new Actions ( driver )
. moveToElement ( tracker , 8 , 0 )
. perform ();
String [] result = driver . findElement ( By . id ( "relative-location" )). getText (). split ( ", " );
Assertions . assertTrue ( Math . abs ( Integer . parseInt ( result [ 0 ] ) - 100 - 8 ) < 2 );
}
@Test
public void moveByOffsetFromViewport () {
driver . get ( "https://www.selenium.dev/selenium/web/mouse_interaction.html" );
PointerInput mouse = new PointerInput ( PointerInput . Kind . MOUSE , "default mouse" );
Sequence actions = new Sequence ( mouse , 0 )
. addAction ( mouse . createPointerMove ( Duration . ZERO , PointerInput . Origin . viewport (), 8 , 12 ));
(( RemoteWebDriver ) driver ). perform ( Collections . singletonList ( actions ));
String [] result = driver . findElement ( By . id ( "absolute-location" )). getText (). split ( ", " );
Assertions . assertTrue ( Math . abs ( Integer . parseInt ( result [ 0 ] ) - 8 ) < 2 );
Assertions . assertTrue ( Math . abs ( Integer . parseInt ( result [ 1 ] ) - 12 ) < 2 );
}
@Test
public void moveByOffsetFromCurrentPointer () {
driver . get ( "https://www.selenium.dev/selenium/web/mouse_interaction.html" );
PointerInput mouse = new PointerInput ( PointerInput . Kind . MOUSE , "default mouse" );
Sequence actions = new Sequence ( mouse , 0 )
. addAction ( mouse . createPointerMove ( Duration . ZERO , PointerInput . Origin . viewport (), 8 , 11 ));
(( RemoteWebDriver ) driver ). perform ( Collections . singletonList ( actions ));
new Actions ( driver )
. moveByOffset ( 13 , 15 )
. perform ();
String [] result = driver . findElement ( By . id ( "absolute-location" )). getText (). split ( ", " );
Assertions . assertTrue ( Math . abs ( Integer . parseInt ( result [ 0 ] ) - 8 - 13 ) < 2 );
Assertions . assertTrue ( Math . abs ( Integer . parseInt ( result [ 1 ] ) - 11 - 15 ) < 2 );
}
@Test
public void dragsToElement () {
driver . get ( "https://www.selenium.dev/selenium/web/mouse_interaction.html" );
WebElement draggable = driver . findElement ( By . id ( "draggable" ));
WebElement droppable = driver . findElement ( By . id ( "droppable" ));
new Actions ( driver )
. dragAndDrop ( draggable , droppable )
. perform ();
Assertions . assertEquals ( "dropped" , driver . findElement ( By . id ( "drop-status" )). getText ());
}
@Test
public void dragsByOffset () {
driver . get ( "https://www.selenium.dev/selenium/web/mouse_interaction.html" );
WebElement draggable = driver . findElement ( By . id ( "draggable" ));
Rectangle start = draggable . getRect ();
Rectangle finish = driver . findElement ( By . id ( "droppable" )). getRect ();
new Actions ( driver )
. dragAndDropBy ( draggable , finish . getX () - start . getX (), finish . getY () - start . getY ())
. perform ();
Assertions . assertEquals ( "dropped" , driver . findElement ( By . id ( "drop-status" )). getText ());
}
}
clickable = driver . find_element ( By . ID , "clickable" )
ActionChains ( driver ) \
. double_click ( clickable ) \
. perform ()
Show full example import pytest
from time import sleep
from selenium.webdriver import ActionChains
from selenium.webdriver.common.actions.action_builder import ActionBuilder
from selenium.webdriver.common.actions.mouse_button import MouseButton
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
def test_click_and_hold ( driver ):
driver . get ( 'https://selenium.dev/selenium/web/mouse_interaction.html' )
clickable = driver . find_element ( By . ID , "clickable" )
ActionChains ( driver ) \
. click_and_hold ( clickable ) \
. perform ()
sleep ( 0.5 )
assert driver . find_element ( By . ID , "click-status" ) . text == "focused"
def test_click_and_release ( driver ):
driver . get ( 'https://selenium.dev/selenium/web/mouse_interaction.html' )
clickable = driver . find_element ( By . ID , "click" )
ActionChains ( driver ) \
. click ( clickable ) \
. perform ()
assert "resultPage.html" in driver . current_url
def test_right_click ( driver ):
driver . get ( 'https://selenium.dev/selenium/web/mouse_interaction.html' )
clickable = driver . find_element ( By . ID , "clickable" )
ActionChains ( driver ) \
. context_click ( clickable ) \
. perform ()
sleep ( 0.5 )
assert driver . find_element ( By . ID , "click-status" ) . text == "context-clicked"
def test_back_click_ab ( driver ):
driver . get ( 'https://selenium.dev/selenium/web/mouse_interaction.html' )
driver . find_element ( By . ID , "click" ) . click ()
assert driver . title == "We Arrive Here"
action = ActionBuilder ( driver )
action . pointer_action . pointer_down ( MouseButton . BACK )
action . pointer_action . pointer_up ( MouseButton . BACK )
action . perform ()
assert driver . title == "BasicMouseInterfaceTest"
def test_forward_click_ab ( driver ):
driver . get ( 'https://selenium.dev/selenium/web/mouse_interaction.html' )
driver . find_element ( By . ID , "click" ) . click ()
driver . back ()
assert driver . title == "BasicMouseInterfaceTest"
action = ActionBuilder ( driver )
action . pointer_action . pointer_down ( MouseButton . FORWARD )
action . pointer_action . pointer_up ( MouseButton . FORWARD )
action . perform ()
assert driver . title == "We Arrive Here"
def test_double_click ( driver ):
driver . get ( 'https://selenium.dev/selenium/web/mouse_interaction.html' )
clickable = driver . find_element ( By . ID , "clickable" )
ActionChains ( driver ) \
. double_click ( clickable ) \
. perform ()
assert driver . find_element ( By . ID , "click-status" ) . text == "double-clicked"
def test_hover ( driver ):
driver . get ( 'https://selenium.dev/selenium/web/mouse_interaction.html' )
hoverable = driver . find_element ( By . ID , "hover" )
ActionChains ( driver ) \
. move_to_element ( hoverable ) \
. perform ()
assert driver . find_element ( By . ID , "move-status" ) . text == "hovered"
def test_move_by_offset_from_element ( driver ):
driver . get ( 'https://selenium.dev/selenium/web/mouse_interaction.html' )
mouse_tracker = driver . find_element ( By . ID , "mouse-tracker" )
ActionChains ( driver ) \
. move_to_element_with_offset ( mouse_tracker , 8 , 0 ) \
. perform ()
coordinates = driver . find_element ( By . ID , "relative-location" ) . text . split ( ", " )
assert abs ( int ( coordinates [ 0 ]) - 100 - 8 ) < 2
def test_move_by_offset_from_viewport_origin_ab ( driver ):
driver . get ( 'https://selenium.dev/selenium/web/mouse_interaction.html' )
WebDriverWait ( driver , 10 ) . until ( EC . presence_of_element_located (( By . ID , "absolute-location" )))
action = ActionBuilder ( driver )
action . pointer_action . move_to_location ( 8 , 0 )
action . perform ()
coordinates = driver . find_element ( By . ID , "absolute-location" ) . text . split ( ", " )
assert abs ( int ( coordinates [ 0 ]) - 8 ) < 2
def test_move_by_offset_from_current_pointer_ab ( driver ):
driver . get ( 'https://selenium.dev/selenium/web/mouse_interaction.html' )
action = ActionBuilder ( driver )
action . pointer_action . move_to_location ( 6 , 3 )
action . perform ()
ActionChains ( driver ) \
. move_by_offset ( 13 , 15 ) \
. perform ()
coordinates = driver . find_element ( By . ID , "absolute-location" ) . text . split ( ", " )
assert abs ( int ( coordinates [ 0 ]) - 6 - 13 ) < 2
assert abs ( int ( coordinates [ 1 ]) - 3 - 15 ) < 2
def test_drag_and_drop_onto_element ( driver ):
driver . get ( 'https://selenium.dev/selenium/web/mouse_interaction.html' )
draggable = driver . find_element ( By . ID , "draggable" )
droppable = driver . find_element ( By . ID , "droppable" )
ActionChains ( driver ) \
. drag_and_drop ( draggable , droppable ) \
. perform ()
assert driver . find_element ( By . ID , "drop-status" ) . text == "dropped"
def test_drag_and_drop_by_offset ( driver ):
driver . get ( 'https://selenium.dev/selenium/web/mouse_interaction.html' )
draggable = driver . find_element ( By . ID , "draggable" )
start = draggable . location
finish = driver . find_element ( By . ID , "droppable" ) . location
ActionChains ( driver ) \
. drag_and_drop_by_offset ( draggable , finish [ 'x' ] - start [ 'x' ], finish [ 'y' ] - start [ 'y' ]) \
. perform ()
assert driver . find_element ( By . ID , "drop-status" ) . text == "dropped"
IWebElement clickable = driver . FindElement ( By . Id ( "clickable" ));
new Actions ( driver )
. DoubleClick ( clickable )
. Perform ();
Show full example using System ;
using System.Drawing ;
using Microsoft.VisualStudio.TestTools.UnitTesting ;
using OpenQA.Selenium ;
using OpenQA.Selenium.Interactions ;
namespace SeleniumDocs.ActionsAPI
{
[TestClass]
public class MouseTest : BaseChromeTest
{
[TestMethod]
public void ClickAndHold ()
{
driver . Url = "https://selenium.dev/selenium/web/mouse_interaction.html" ;
IWebElement clickable = driver . FindElement ( By . Id ( "clickable" ));
new Actions ( driver )
. ClickAndHold ( clickable )
. Perform ();
Assert . AreEqual ( "focused" , driver . FindElement ( By . Id ( "click-status" )). Text );
}
[TestMethod]
public void ClickAndRelease ()
{
driver . Url = "https://selenium.dev/selenium/web/mouse_interaction.html" ;
IWebElement clickable = driver . FindElement ( By . Id ( "click" ));
new Actions ( driver )
. Click ( clickable )
. Perform ();
Assert . IsTrue ( driver . Url . Contains ( "resultPage.html" ));
}
[TestMethod]
public void RightClick ()
{
driver . Url = "https://selenium.dev/selenium/web/mouse_interaction.html" ;
IWebElement clickable = driver . FindElement ( By . Id ( "clickable" ));
new Actions ( driver )
. ContextClick ( clickable )
. Perform ();
Assert . AreEqual ( "context-clicked" , driver . FindElement ( By . Id ( "click-status" )). Text );
}
[TestMethod]
public void BackClick ()
{
driver . Url = "https://selenium.dev/selenium/web/mouse_interaction.html" ;
driver . FindElement ( By . Id ( "click" )). Click ();
Assert . AreEqual ( "We Arrive Here" , driver . Title );
ActionBuilder actionBuilder = new ActionBuilder ();
PointerInputDevice mouse = new PointerInputDevice ( PointerKind . Mouse , "default mouse" );
actionBuilder . AddAction ( mouse . CreatePointerDown ( MouseButton . Back ));
actionBuilder . AddAction ( mouse . CreatePointerUp ( MouseButton . Back ));
(( IActionExecutor ) driver ). PerformActions ( actionBuilder . ToActionSequenceList ());
Assert . AreEqual ( "BasicMouseInterfaceTest" , driver . Title );
}
[TestMethod]
public void ForwardClick ()
{
driver . Url = "https://selenium.dev/selenium/web/mouse_interaction.html" ;
driver . FindElement ( By . Id ( "click" )). Click ();
driver . Navigate (). Back ();
Assert . AreEqual ( "BasicMouseInterfaceTest" , driver . Title );
ActionBuilder actionBuilder = new ActionBuilder ();
PointerInputDevice mouse = new PointerInputDevice ( PointerKind . Mouse , "default mouse" );
actionBuilder . AddAction ( mouse . CreatePointerDown ( MouseButton . Forward ));
actionBuilder . AddAction ( mouse . CreatePointerUp ( MouseButton . Forward ));
(( IActionExecutor ) driver ). PerformActions ( actionBuilder . ToActionSequenceList ());
Assert . AreEqual ( "We Arrive Here" , driver . Title );
}
[TestMethod]
public void DoubleClick ()
{
driver . Url = "https://selenium.dev/selenium/web/mouse_interaction.html" ;
IWebElement clickable = driver . FindElement ( By . Id ( "clickable" ));
new Actions ( driver )
. DoubleClick ( clickable )
. Perform ();
Assert . AreEqual ( "double-clicked" , driver . FindElement ( By . Id ( "click-status" )). Text );
}
[TestMethod]
public void Hovers ()
{
driver . Url = "https://selenium.dev/selenium/web/mouse_interaction.html" ;
IWebElement hoverable = driver . FindElement ( By . Id ( "hover" ));
new Actions ( driver )
. MoveToElement ( hoverable )
. Perform ();
Assert . AreEqual ( "hovered" , driver . FindElement ( By . Id ( "move-status" )). Text );
}
[TestMethod]
[Obsolete("Obsolete")]
public void MoveByOffsetFromTopLeftOfElement ()
{
driver . Url = "https://selenium.dev/selenium/web/mouse_interaction.html" ;
IWebElement tracker = driver . FindElement ( By . Id ( "mouse-tracker" ));
new Actions ( driver )
. MoveToElement ( tracker , 8 , 0 )
. Perform ();
string [] result = driver . FindElement ( By . Id ( "relative-location" )). Text . Split ( ", " );
Assert . IsTrue ( Math . Abs ( int . Parse ( result [ 0 ]) - 100 - 8 ) < 2 );
}
[TestMethod]
public void MoveByOffsetFromCenterOfElement ()
{
driver . Url = "https://selenium.dev/selenium/web/mouse_interaction.html" ;
IWebElement tracker = driver . FindElement ( By . Id ( "mouse-tracker" ));
new Actions ( driver )
. MoveToElement ( tracker , 8 , 0 )
. Perform ();
string [] result = driver . FindElement ( By . Id ( "relative-location" )). Text . Split ( ", " );
Assert . IsTrue ( Math . Abs ( int . Parse ( result [ 0 ]) - 100 - 8 ) < 2 );
}
[TestMethod]
public void MoveByOffsetFromViewport ()
{
driver . Url = "https://selenium.dev/selenium/web/mouse_interaction.html" ;
ActionBuilder actionBuilder = new ActionBuilder ();
PointerInputDevice mouse = new PointerInputDevice ( PointerKind . Mouse , "default mouse" );
actionBuilder . AddAction ( mouse . CreatePointerMove ( CoordinateOrigin . Viewport ,
8 , 0 , TimeSpan . Zero ));
(( IActionExecutor ) driver ). PerformActions ( actionBuilder . ToActionSequenceList ());
string [] result = driver . FindElement ( By . Id ( "absolute-location" )). Text . Split ( ", " );
Assert . IsTrue ( Math . Abs ( int . Parse ( result [ 0 ]) - 8 ) < 2 );
}
[TestMethod]
public void MoveByOffsetFromCurrentPointerLocation ()
{
driver . Url = "https://selenium.dev/selenium/web/mouse_interaction.html" ;
ActionBuilder actionBuilder = new ActionBuilder ();
PointerInputDevice mouse = new PointerInputDevice ( PointerKind . Mouse , "default mouse" );
actionBuilder . AddAction ( mouse . CreatePointerMove ( CoordinateOrigin . Viewport ,
8 , 12 , TimeSpan . Zero ));
(( IActionExecutor ) driver ). PerformActions ( actionBuilder . ToActionSequenceList ());
new Actions ( driver )
. MoveByOffset ( 13 , 15 )
. Perform ();
string [] result = driver . FindElement ( By . Id ( "absolute-location" )). Text . Split ( ", " );
Assert . IsTrue ( Math . Abs ( int . Parse ( result [ 0 ]) - 8 - 13 ) < 2 );
Assert . IsTrue ( Math . Abs ( int . Parse ( result [ 1 ]) - 12 - 15 ) < 2 );
}
[TestMethod]
public void DragToElement ()
{
driver . Url = "https://selenium.dev/selenium/web/mouse_interaction.html" ;
IWebElement draggable = driver . FindElement ( By . Id ( "draggable" ));
IWebElement droppable = driver . FindElement ( By . Id ( "droppable" ));
new Actions ( driver )
. DragAndDrop ( draggable , droppable )
. Perform ();
Assert . AreEqual ( "dropped" , driver . FindElement ( By . Id ( "drop-status" )). Text );
}
[TestMethod]
public void DragByOffset ()
{
driver . Url = "https://selenium.dev/selenium/web/mouse_interaction.html" ;
IWebElement draggable = driver . FindElement ( By . Id ( "draggable" ));
Point start = draggable . Location ;
Point finish = driver . FindElement ( By . Id ( "droppable" )). Location ;
new Actions ( driver )
. DragAndDropToOffset ( draggable , finish . X - start . X , finish . Y - start . Y )
. Perform ();
Assert . AreEqual ( "dropped" , driver . FindElement ( By . Id ( "drop-status" )). Text );
}
}
}
clickable = driver . find_element ( id : 'clickable' )
driver . action
. double_click ( clickable )
. perform
Show full example # frozen_string_literal: true
require 'spec_helper'
RSpec . describe 'Mouse' do
let ( :driver ) { start_session }
it 'click and hold' do
driver . get 'https://www.selenium.dev/selenium/web/mouse_interaction.html'
clickable = driver . find_element ( id : 'clickable' )
driver . action
. click_and_hold ( clickable )
. perform
expect ( driver . find_element ( id : 'click-status' ) . text ) . to eq 'focused'
end
it 'click and release' do
driver . get 'https://www.selenium.dev/selenium/web/mouse_interaction.html'
clickable = driver . find_element ( id : 'click' )
driver . action
. click ( clickable )
. perform
expect ( driver . current_url ) . to include 'resultPage.html'
end
describe 'alternate button clicks' do
it 'right click' do
driver . get 'https://www.selenium.dev/selenium/web/mouse_interaction.html'
clickable = driver . find_element ( id : 'clickable' )
driver . action
. context_click ( clickable )
. perform
expect ( driver . find_element ( id : 'click-status' ) . text ) . to eq 'context-clicked'
end
it 'back click' do
driver . get 'https://www.selenium.dev/selenium/web/mouse_interaction.html'
driver . find_element ( id : 'click' ) . click
expect ( driver . title ) . to eq ( 'We Arrive Here' )
driver . action
. pointer_down ( :back )
. pointer_up ( :back )
. perform
expect ( driver . title ) . to eq ( 'BasicMouseInterfaceTest' )
end
it 'forward click' do
driver . get 'https://www.selenium.dev/selenium/web/mouse_interaction.html'
driver . find_element ( id : 'click' ) . click
driver . navigate . back
expect ( driver . title ) . to eq ( 'BasicMouseInterfaceTest' )
driver . action
. pointer_down ( :forward )
. pointer_up ( :forward )
. perform
expect ( driver . title ) . to eq ( 'We Arrive Here' )
end
end
it 'double click' do
driver . get 'https://www.selenium.dev/selenium/web/mouse_interaction.html'
clickable = driver . find_element ( id : 'clickable' )
driver . action
. double_click ( clickable )
. perform
expect ( driver . find_element ( id : 'click-status' ) . text ) . to eq 'double-clicked'
end
it 'hovers' do
driver . get 'https://www.selenium.dev/selenium/web/mouse_interaction.html'
hoverable = driver . find_element ( id : 'hover' )
driver . action
. move_to ( hoverable )
. perform
expect ( driver . find_element ( id : 'move-status' ) . text ) . to eq 'hovered'
end
describe 'move by offset' do
it 'offset from element' do
driver . get 'https://www.selenium.dev/selenium/web/mouse_interaction.html'
driver . action . scroll_to ( driver . find_element ( id : 'bottom' )) . perform
mouse_tracker = driver . find_element ( id : 'mouse-tracker' )
driver . action
. move_to ( mouse_tracker , 8 , 11 )
. perform
rect = mouse_tracker . rect
center_x = rect . width / 2
center_y = rect . height / 2
x_coord , y_coord = driver . find_element ( id : 'relative-location' ) . text . split ( ',' ) . map ( & :to_i )
expect ( x_coord ) . to be_within ( 1 ) . of ( center_x + 8 )
expect ( y_coord ) . to be_within ( 1 ) . of ( center_y + 11 )
end
it 'offset from viewport' do
driver . get 'https://www.selenium.dev/selenium/web/mouse_interaction.html'
driver . action
. move_to_location ( 8 , 12 )
. perform
x_coord , y_coord = driver . find_element ( id : 'absolute-location' ) . text . split ( ',' ) . map ( & :to_i )
expect ( x_coord ) . to be_within ( 1 ) . of ( 8 )
expect ( y_coord ) . to be_within ( 1 ) . of ( 12 )
end
it 'offset from current pointer location' do
driver . get 'https://www.selenium.dev/selenium/web/mouse_interaction.html'
driver . action . move_to_location ( 8 , 11 ) . perform
driver . action
. move_by ( 13 , 15 )
. perform
x_coord , y_coord = driver . find_element ( id : 'absolute-location' ) . text . split ( ',' ) . map ( & :to_i )
expect ( x_coord ) . to be_within ( 1 ) . of ( 8 + 13 )
expect ( y_coord ) . to be_within ( 1 ) . of ( 11 + 15 )
end
end
it 'drags to another element' do
driver . get 'https://www.selenium.dev/selenium/web/mouse_interaction.html'
draggable = driver . find_element ( id : 'draggable' )
droppable = driver . find_element ( id : 'droppable' )
driver . action
. drag_and_drop ( draggable , droppable )
. perform
expect ( driver . find_element ( id : 'drop-status' ) . text ) . to include ( 'dropped' )
end
it 'drags by an offset' do
driver . get 'https://www.selenium.dev/selenium/web/mouse_interaction.html'
draggable = driver . find_element ( id : 'draggable' )
start = draggable . rect
finish = driver . find_element ( id : 'droppable' ) . rect
driver . action
. drag_and_drop_by ( draggable , finish . x - start . x , finish . y - start . y )
. perform
expect ( driver . find_element ( id : 'drop-status' ) . text ) . to include ( 'dropped' )
end
end
const clickable = driver . findElement ( By . id ( "clickable" ));
const actions = driver . actions ({ async : true });
await actions . doubleClick ( clickable ). perform ();
Show full example const { By , Builder } = require ( 'selenium-webdriver' );
const assert = require ( "assert" );
describe ( 'Double click' , function () {
let driver ;
before ( async function () {
driver = new Builder (). forBrowser ( 'chrome' ). build ();
});
after ( async () => await driver . quit ());
it ( 'Double-click on an element' , async function () {
await driver . get ( 'https://www.selenium.dev/selenium/web/mouse_interaction.html' );
const clickable = driver . findElement ( By . id ( "clickable" ));
const actions = driver . actions ({ async : true });
await actions . doubleClick ( clickable ). perform ();
await driver . sleep ( 500 );
const status = await driver . findElement ( By . id ( 'click-status' )). getText ();
assert . deepStrictEqual ( status , `double-clicked` )
});
});
val clickable = driver . findElement ( By . id ( "clickable" ))
Actions ( driver )
. doubleClick ( clickable )
. perform ()
Show full example 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.Rectangle
import org.openqa.selenium.WebElement
import org.openqa.selenium.interactions.Actions
import org.openqa.selenium.interactions.PointerInput
import org.openqa.selenium.interactions.Sequence
import org.openqa.selenium.remote.RemoteWebDriver
import java.time.Duration
import java.util.Collections
class MouseTest : BaseTest () {
@Test
fun clickAndHold () {
driver . get ( "https://www.selenium.dev/selenium/web/mouse_interaction.html" )
val clickable = driver . findElement ( By . id ( "clickable" ))
Actions ( driver )
. clickAndHold ( clickable )
. perform ()
Assertions . assertEquals ( "focused" , driver . findElement ( By . id ( "click-status" )). getText ())
}
@Test
fun clickAndRelease () {
driver . get ( "https://www.selenium.dev/selenium/web/mouse_interaction.html" )
val clickable = driver . findElement ( By . id ( "click" ))
Actions ( driver )
. click ( clickable )
. perform ()
Assertions . assertTrue ( driver . getCurrentUrl () !! . contains ( "resultPage.html" ))
}
@Test
fun rightClick () {
driver . get ( "https://www.selenium.dev/selenium/web/mouse_interaction.html" )
val clickable = driver . findElement ( By . id ( "clickable" ))
Actions ( driver )
. contextClick ( clickable )
. perform ()
Assertions . assertEquals ( "context-clicked" , driver . findElement ( By . id ( "click-status" )). getText ())
}
@Test
fun backClick () {
driver . get ( "https://www.selenium.dev/selenium/web/mouse_interaction.html" )
driver . findElement ( By . id ( "click" )). click ()
Assertions . assertEquals ( driver . getTitle (), "We Arrive Here" )
val mouse = PointerInput ( PointerInput . Kind . MOUSE , "default mouse" )
val actions = Sequence ( mouse , 0 )
. addAction ( mouse . createPointerDown ( PointerInput . MouseButton . BACK . asArg ()))
. addAction ( mouse . createPointerUp ( PointerInput . MouseButton . BACK . asArg ()))
( driver as RemoteWebDriver ). perform ( Collections . singletonList ( actions ))
Assertions . assertEquals ( "BasicMouseInterfaceTest" , driver . getTitle ())
}
@Test
fun forwardClick () {
driver . get ( "https://www.selenium.dev/selenium/web/mouse_interaction.html" )
driver . findElement ( By . id ( "click" )). click ()
driver . navigate (). back ()
Assertions . assertEquals ( driver . getTitle (), "BasicMouseInterfaceTest" )
val mouse = PointerInput ( PointerInput . Kind . MOUSE , "default mouse" )
val actions = Sequence ( mouse , 0 )
. addAction ( mouse . createPointerDown ( PointerInput . MouseButton . FORWARD . asArg ()))
. addAction ( mouse . createPointerUp ( PointerInput . MouseButton . FORWARD . asArg ()))
( driver as RemoteWebDriver ). perform ( Collections . singletonList ( actions ))
Assertions . assertEquals ( "We Arrive Here" , driver . getTitle ())
}
@Test
fun doubleClick () {
driver . get ( "https://www.selenium.dev/selenium/web/mouse_interaction.html" )
val clickable = driver . findElement ( By . id ( "clickable" ))
Actions ( driver )
. doubleClick ( clickable )
. perform ()
Assertions . assertEquals ( "double-clicked" , driver . findElement ( By . id ( "click-status" )). getText ())
}
@Test
fun hovers () {
driver . get ( "https://www.selenium.dev/selenium/web/mouse_interaction.html" )
val hoverable = driver . findElement ( By . id ( "hover" ))
Actions ( driver )
. moveToElement ( hoverable )
. perform ()
Assertions . assertEquals ( "hovered" , driver . findElement ( By . id ( "move-status" )). getText ())
}
@Test
fun moveByOffsetFromElement () {
driver . get ( "https://www.selenium.dev/selenium/web/mouse_interaction.html" )
driver . manage (). window (). fullscreen ()
val tracker = driver . findElement ( By . id ( "mouse-tracker" ))
Actions ( driver )
. moveToElement ( tracker , 8 , 0 )
. perform ()
val result = driver . findElement ( By . id ( "relative-location" )). getText (). split ( ", " )
Assertions . assertTrue ( Math . abs ( Integer . parseInt ( result [ 0 ]) - 100 - 8 ) < 2 )
}
@Test
fun moveByOffsetFromViewport () {
driver . get ( "https://www.selenium.dev/selenium/web/mouse_interaction.html" )
val mouse = PointerInput ( PointerInput . Kind . MOUSE , "default mouse" )
val actions = Sequence ( mouse , 0 )
. addAction ( mouse . createPointerMove ( Duration . ZERO , PointerInput . Origin . viewport (), 8 , 12 ))
( driver as RemoteWebDriver ). perform ( Collections . singletonList ( actions ))
val result = driver . findElement ( By . id ( "absolute-location" )). getText (). split ( ", " )
Assertions . assertTrue ( Math . abs ( Integer . parseInt ( result [ 0 ]) - 8 ) < 2 )
Assertions . assertTrue ( Math . abs ( Integer . parseInt ( result [ 1 ]) - 12 ) < 2 )
}
@Test
fun moveByOffsetFromCurrentPointer () {
driver . get ( "https://www.selenium.dev/selenium/web/mouse_interaction.html" )
val mouse = PointerInput ( PointerInput . Kind . MOUSE , "default mouse" )
val actions = Sequence ( mouse , 0 )
. addAction ( mouse . createPointerMove ( Duration . ZERO , PointerInput . Origin . viewport (), 8 , 11 ))
( driver as RemoteWebDriver ). perform ( Collections . singletonList ( actions ))
Actions ( driver )
. moveByOffset ( 13 , 15 )
. perform ()
val result = driver . findElement ( By . id ( "absolute-location" )). getText (). split ( ", " )
Assertions . assertTrue ( Math . abs ( Integer . parseInt ( result [ 0 ]) - 8 - 13 ) < 2 )
Assertions . assertTrue ( Math . abs ( Integer . parseInt ( result [ 1 ]) - 11 - 15 ) < 2 )
}
@Test
fun dragsToElement () {
driver . get ( "https://www.selenium.dev/selenium/web/mouse_interaction.html" )
val draggable = driver . findElement ( By . id ( "draggable" ))
val droppable = driver . findElement ( By . id ( "droppable" ))
Actions ( driver )
. dragAndDrop ( draggable , droppable )
. perform ()
Assertions . assertEquals ( "dropped" , driver . findElement ( By . id ( "drop-status" )). getText ())
}
@Test
fun dragsByOffset () {
driver . get ( "https://www.selenium.dev/selenium/web/mouse_interaction.html" )
val draggable = driver . findElement ( By . id ( "draggable" ))
val start = draggable . getRect ()
val finish = driver . findElement ( By . id ( "droppable" )). getRect ()
Actions ( driver )
. dragAndDropBy ( draggable , finish . getX () - start . getX (), finish . getY () - start . getY ())
. perform ()
Assertions . assertEquals ( "dropped" , driver . findElement ( By . id ( "drop-status" )). getText ())
}
}
Mover para o Elemento Este método move o mouse para o ponto central do elemento que está visível na tela. Isso é conhecido como “hovering” ou “pairar”. É importante observar que o elemento deve estar no viewport (área visível na tela) ou então o comando resultará em erro.
Java
Python
CSharp
Ruby
JavaScript
Kotlin WebElement hoverable = driver . findElement ( By . id ( "hover" ));
new Actions ( driver )
. moveToElement ( hoverable )
. perform ();
Show full example 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.Rectangle ;
import org.openqa.selenium.WebElement ;
import org.openqa.selenium.interactions.Actions ;
import org.openqa.selenium.interactions.PointerInput ;
import org.openqa.selenium.interactions.Sequence ;
import org.openqa.selenium.remote.RemoteWebDriver ;
import java.time.Duration ;
import java.util.Collections ;
public class MouseTest extends BaseChromeTest {
@Test
public void clickAndHold () {
driver . get ( "https://www.selenium.dev/selenium/web/mouse_interaction.html" );
WebElement clickable = driver . findElement ( By . id ( "clickable" ));
new Actions ( driver )
. clickAndHold ( clickable )
. perform ();
Assertions . assertEquals ( "focused" , driver . findElement ( By . id ( "click-status" )). getText ());
}
@Test
public void clickAndRelease () {
driver . get ( "https://www.selenium.dev/selenium/web/mouse_interaction.html" );
WebElement clickable = driver . findElement ( By . id ( "click" ));
new Actions ( driver )
. click ( clickable )
. perform ();
Assertions . assertTrue ( driver . getCurrentUrl (). contains ( "resultPage.html" ));
}
@Test
public void rightClick () {
driver . get ( "https://www.selenium.dev/selenium/web/mouse_interaction.html" );
WebElement clickable = driver . findElement ( By . id ( "clickable" ));
new Actions ( driver )
. contextClick ( clickable )
. perform ();
Assertions . assertEquals ( "context-clicked" , driver . findElement ( By . id ( "click-status" )). getText ());
}
@Test
public void backClick () {
driver . get ( "https://www.selenium.dev/selenium/web/mouse_interaction.html" );
driver . findElement ( By . id ( "click" )). click ();
Assertions . assertEquals ( driver . getTitle (), "We Arrive Here" );
PointerInput mouse = new PointerInput ( PointerInput . Kind . MOUSE , "default mouse" );
Sequence actions = new Sequence ( mouse , 0 )
. addAction ( mouse . createPointerDown ( PointerInput . MouseButton . BACK . asArg ()))
. addAction ( mouse . createPointerUp ( PointerInput . MouseButton . BACK . asArg ()));
(( RemoteWebDriver ) driver ). perform ( Collections . singletonList ( actions ));
Assertions . assertEquals ( "BasicMouseInterfaceTest" , driver . getTitle ());
}
@Test
public void forwardClick () {
driver . get ( "https://www.selenium.dev/selenium/web/mouse_interaction.html" );
driver . findElement ( By . id ( "click" )). click ();
driver . navigate (). back ();
Assertions . assertEquals ( driver . getTitle (), "BasicMouseInterfaceTest" );
PointerInput mouse = new PointerInput ( PointerInput . Kind . MOUSE , "default mouse" );
Sequence actions = new Sequence ( mouse , 0 )
. addAction ( mouse . createPointerDown ( PointerInput . MouseButton . FORWARD . asArg ()))
. addAction ( mouse . createPointerUp ( PointerInput . MouseButton . FORWARD . asArg ()));
(( RemoteWebDriver ) driver ). perform ( Collections . singletonList ( actions ));
Assertions . assertEquals ( "We Arrive Here" , driver . getTitle ());
}
@Test
public void doubleClick () {
driver . get ( "https://www.selenium.dev/selenium/web/mouse_interaction.html" );
WebElement clickable = driver . findElement ( By . id ( "clickable" ));
new Actions ( driver )
. doubleClick ( clickable )
. perform ();
Assertions . assertEquals ( "double-clicked" , driver . findElement ( By . id ( "click-status" )). getText ());
}
@Test
public void hovers () {
driver . get ( "https://www.selenium.dev/selenium/web/mouse_interaction.html" );
WebElement hoverable = driver . findElement ( By . id ( "hover" ));
new Actions ( driver )
. moveToElement ( hoverable )
. perform ();
Assertions . assertEquals ( "hovered" , driver . findElement ( By . id ( "move-status" )). getText ());
}
@Test
public void moveByOffsetFromElement () {
driver . get ( "https://www.selenium.dev/selenium/web/mouse_interaction.html" );
driver . manage (). window (). fullscreen ();
WebElement tracker = driver . findElement ( By . id ( "mouse-tracker" ));
new Actions ( driver )
. moveToElement ( tracker , 8 , 0 )
. perform ();
String [] result = driver . findElement ( By . id ( "relative-location" )). getText (). split ( ", " );
Assertions . assertTrue ( Math . abs ( Integer . parseInt ( result [ 0 ] ) - 100 - 8 ) < 2 );
}
@Test
public void moveByOffsetFromViewport () {
driver . get ( "https://www.selenium.dev/selenium/web/mouse_interaction.html" );
PointerInput mouse = new PointerInput ( PointerInput . Kind . MOUSE , "default mouse" );
Sequence actions = new Sequence ( mouse , 0 )
. addAction ( mouse . createPointerMove ( Duration . ZERO , PointerInput . Origin . viewport (), 8 , 12 ));
(( RemoteWebDriver ) driver ). perform ( Collections . singletonList ( actions ));
String [] result = driver . findElement ( By . id ( "absolute-location" )). getText (). split ( ", " );
Assertions . assertTrue ( Math . abs ( Integer . parseInt ( result [ 0 ] ) - 8 ) < 2 );
Assertions . assertTrue ( Math . abs ( Integer . parseInt ( result [ 1 ] ) - 12 ) < 2 );
}
@Test
public void moveByOffsetFromCurrentPointer () {
driver . get ( "https://www.selenium.dev/selenium/web/mouse_interaction.html" );
PointerInput mouse = new PointerInput ( PointerInput . Kind . MOUSE , "default mouse" );
Sequence actions = new Sequence ( mouse , 0 )
. addAction ( mouse . createPointerMove ( Duration . ZERO , PointerInput . Origin . viewport (), 8 , 11 ));
(( RemoteWebDriver ) driver ). perform ( Collections . singletonList ( actions ));
new Actions ( driver )
. moveByOffset ( 13 , 15 )
. perform ();
String [] result = driver . findElement ( By . id ( "absolute-location" )). getText (). split ( ", " );
Assertions . assertTrue ( Math . abs ( Integer . parseInt ( result [ 0 ] ) - 8 - 13 ) < 2 );
Assertions . assertTrue ( Math . abs ( Integer . parseInt ( result [ 1 ] ) - 11 - 15 ) < 2 );
}
@Test
public void dragsToElement () {
driver . get ( "https://www.selenium.dev/selenium/web/mouse_interaction.html" );
WebElement draggable = driver . findElement ( By . id ( "draggable" ));
WebElement droppable = driver . findElement ( By . id ( "droppable" ));
new Actions ( driver )
. dragAndDrop ( draggable , droppable )
. perform ();
Assertions . assertEquals ( "dropped" , driver . findElement ( By . id ( "drop-status" )). getText ());
}
@Test
public void dragsByOffset () {
driver . get ( "https://www.selenium.dev/selenium/web/mouse_interaction.html" );
WebElement draggable = driver . findElement ( By . id ( "draggable" ));
Rectangle start = draggable . getRect ();
Rectangle finish = driver . findElement ( By . id ( "droppable" )). getRect ();
new Actions ( driver )
. dragAndDropBy ( draggable , finish . getX () - start . getX (), finish . getY () - start . getY ())
. perform ();
Assertions . assertEquals ( "dropped" , driver . findElement ( By . id ( "drop-status" )). getText ());
}
}
hoverable = driver . find_element ( By . ID , "hover" )
ActionChains ( driver ) \
. move_to_element ( hoverable ) \
. perform ()
Show full example import pytest
from time import sleep
from selenium.webdriver import ActionChains
from selenium.webdriver.common.actions.action_builder import ActionBuilder
from selenium.webdriver.common.actions.mouse_button import MouseButton
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
def test_click_and_hold ( driver ):
driver . get ( 'https://selenium.dev/selenium/web/mouse_interaction.html' )
clickable = driver . find_element ( By . ID , "clickable" )
ActionChains ( driver ) \
. click_and_hold ( clickable ) \
. perform ()
sleep ( 0.5 )
assert driver . find_element ( By . ID , "click-status" ) . text == "focused"
def test_click_and_release ( driver ):
driver . get ( 'https://selenium.dev/selenium/web/mouse_interaction.html' )
clickable = driver . find_element ( By . ID , "click" )
ActionChains ( driver ) \
. click ( clickable ) \
. perform ()
assert "resultPage.html" in driver . current_url
def test_right_click ( driver ):
driver . get ( 'https://selenium.dev/selenium/web/mouse_interaction.html' )
clickable = driver . find_element ( By . ID , "clickable" )
ActionChains ( driver ) \
. context_click ( clickable ) \
. perform ()
sleep ( 0.5 )
assert driver . find_element ( By . ID , "click-status" ) . text == "context-clicked"
def test_back_click_ab ( driver ):
driver . get ( 'https://selenium.dev/selenium/web/mouse_interaction.html' )
driver . find_element ( By . ID , "click" ) . click ()
assert driver . title == "We Arrive Here"
action = ActionBuilder ( driver )
action . pointer_action . pointer_down ( MouseButton . BACK )
action . pointer_action . pointer_up ( MouseButton . BACK )
action . perform ()
assert driver . title == "BasicMouseInterfaceTest"
def test_forward_click_ab ( driver ):
driver . get ( 'https://selenium.dev/selenium/web/mouse_interaction.html' )
driver . find_element ( By . ID , "click" ) . click ()
driver . back ()
assert driver . title == "BasicMouseInterfaceTest"
action = ActionBuilder ( driver )
action . pointer_action . pointer_down ( MouseButton . FORWARD )
action . pointer_action . pointer_up ( MouseButton . FORWARD )
action . perform ()
assert driver . title == "We Arrive Here"
def test_double_click ( driver ):
driver . get ( 'https://selenium.dev/selenium/web/mouse_interaction.html' )
clickable = driver . find_element ( By . ID , "clickable" )
ActionChains ( driver ) \
. double_click ( clickable ) \
. perform ()
assert driver . find_element ( By . ID , "click-status" ) . text == "double-clicked"
def test_hover ( driver ):
driver . get ( 'https://selenium.dev/selenium/web/mouse_interaction.html' )
hoverable = driver . find_element ( By . ID , "hover" )
ActionChains ( driver ) \
. move_to_element ( hoverable ) \
. perform ()
assert driver . find_element ( By . ID , "move-status" ) . text == "hovered"
def test_move_by_offset_from_element ( driver ):
driver . get ( 'https://selenium.dev/selenium/web/mouse_interaction.html' )
mouse_tracker = driver . find_element ( By . ID , "mouse-tracker" )
ActionChains ( driver ) \
. move_to_element_with_offset ( mouse_tracker , 8 , 0 ) \
. perform ()
coordinates = driver . find_element ( By . ID , "relative-location" ) . text . split ( ", " )
assert abs ( int ( coordinates [ 0 ]) - 100 - 8 ) < 2
def test_move_by_offset_from_viewport_origin_ab ( driver ):
driver . get ( 'https://selenium.dev/selenium/web/mouse_interaction.html' )
WebDriverWait ( driver , 10 ) . until ( EC . presence_of_element_located (( By . ID , "absolute-location" )))
action = ActionBuilder ( driver )
action . pointer_action . move_to_location ( 8 , 0 )
action . perform ()
coordinates = driver . find_element ( By . ID , "absolute-location" ) . text . split ( ", " )
assert abs ( int ( coordinates [ 0 ]) - 8 ) < 2
def test_move_by_offset_from_current_pointer_ab ( driver ):
driver . get ( 'https://selenium.dev/selenium/web/mouse_interaction.html' )
action = ActionBuilder ( driver )
action . pointer_action . move_to_location ( 6 , 3 )
action . perform ()
ActionChains ( driver ) \
. move_by_offset ( 13 , 15 ) \
. perform ()
coordinates = driver . find_element ( By . ID , "absolute-location" ) . text . split ( ", " )
assert abs ( int ( coordinates [ 0 ]) - 6 - 13 ) < 2
assert abs ( int ( coordinates [ 1 ]) - 3 - 15 ) < 2
def test_drag_and_drop_onto_element ( driver ):
driver . get ( 'https://selenium.dev/selenium/web/mouse_interaction.html' )
draggable = driver . find_element ( By . ID , "draggable" )
droppable = driver . find_element ( By . ID , "droppable" )
ActionChains ( driver ) \
. drag_and_drop ( draggable , droppable ) \
. perform ()
assert driver . find_element ( By . ID , "drop-status" ) . text == "dropped"
def test_drag_and_drop_by_offset ( driver ):
driver . get ( 'https://selenium.dev/selenium/web/mouse_interaction.html' )
draggable = driver . find_element ( By . ID , "draggable" )
start = draggable . location
finish = driver . find_element ( By . ID , "droppable" ) . location
ActionChains ( driver ) \
. drag_and_drop_by_offset ( draggable , finish [ 'x' ] - start [ 'x' ], finish [ 'y' ] - start [ 'y' ]) \
. perform ()
assert driver . find_element ( By . ID , "drop-status" ) . text == "dropped"
IWebElement hoverable = driver . FindElement ( By . Id ( "hover" ));
new Actions ( driver )
. MoveToElement ( hoverable )
. Perform ();
Show full example using System ;
using System.Drawing ;
using Microsoft.VisualStudio.TestTools.UnitTesting ;
using OpenQA.Selenium ;
using OpenQA.Selenium.Interactions ;
namespace SeleniumDocs.ActionsAPI
{
[TestClass]
public class MouseTest : BaseChromeTest
{
[TestMethod]
public void ClickAndHold ()
{
driver . Url = "https://selenium.dev/selenium/web/mouse_interaction.html" ;
IWebElement clickable = driver . FindElement ( By . Id ( "clickable" ));
new Actions ( driver )
. ClickAndHold ( clickable )
. Perform ();
Assert . AreEqual ( "focused" , driver . FindElement ( By . Id ( "click-status" )). Text );
}
[TestMethod]
public void ClickAndRelease ()
{
driver . Url = "https://selenium.dev/selenium/web/mouse_interaction.html" ;
IWebElement clickable = driver . FindElement ( By . Id ( "click" ));
new Actions ( driver )
. Click ( clickable )
. Perform ();
Assert . IsTrue ( driver . Url . Contains ( "resultPage.html" ));
}
[TestMethod]
public void RightClick ()
{
driver . Url = "https://selenium.dev/selenium/web/mouse_interaction.html" ;
IWebElement clickable = driver . FindElement ( By . Id ( "clickable" ));
new Actions ( driver )
. ContextClick ( clickable )
. Perform ();
Assert . AreEqual ( "context-clicked" , driver . FindElement ( By . Id ( "click-status" )). Text );
}
[TestMethod]
public void BackClick ()
{
driver . Url = "https://selenium.dev/selenium/web/mouse_interaction.html" ;
driver . FindElement ( By . Id ( "click" )). Click ();
Assert . AreEqual ( "We Arrive Here" , driver . Title );
ActionBuilder actionBuilder = new ActionBuilder ();
PointerInputDevice mouse = new PointerInputDevice ( PointerKind . Mouse , "default mouse" );
actionBuilder . AddAction ( mouse . CreatePointerDown ( MouseButton . Back ));
actionBuilder . AddAction ( mouse . CreatePointerUp ( MouseButton . Back ));
(( IActionExecutor ) driver ). PerformActions ( actionBuilder . ToActionSequenceList ());
Assert . AreEqual ( "BasicMouseInterfaceTest" , driver . Title );
}
[TestMethod]
public void ForwardClick ()
{
driver . Url = "https://selenium.dev/selenium/web/mouse_interaction.html" ;
driver . FindElement ( By . Id ( "click" )). Click ();
driver . Navigate (). Back ();
Assert . AreEqual ( "BasicMouseInterfaceTest" , driver . Title );
ActionBuilder actionBuilder = new ActionBuilder ();
PointerInputDevice mouse = new PointerInputDevice ( PointerKind . Mouse , "default mouse" );
actionBuilder . AddAction ( mouse . CreatePointerDown ( MouseButton . Forward ));
actionBuilder . AddAction ( mouse . CreatePointerUp ( MouseButton . Forward ));
(( IActionExecutor ) driver ). PerformActions ( actionBuilder . ToActionSequenceList ());
Assert . AreEqual ( "We Arrive Here" , driver . Title );
}
[TestMethod]
public void DoubleClick ()
{
driver . Url = "https://selenium.dev/selenium/web/mouse_interaction.html" ;
IWebElement clickable = driver . FindElement ( By . Id ( "clickable" ));
new Actions ( driver )
. DoubleClick ( clickable )
. Perform ();
Assert . AreEqual ( "double-clicked" , driver . FindElement ( By . Id ( "click-status" )). Text );
}
[TestMethod]
public void Hovers ()
{
driver . Url = "https://selenium.dev/selenium/web/mouse_interaction.html" ;
IWebElement hoverable = driver . FindElement ( By . Id ( "hover" ));
new Actions ( driver )
. MoveToElement ( hoverable )
. Perform ();
Assert . AreEqual ( "hovered" , driver . FindElement ( By . Id ( "move-status" )). Text );
}
[TestMethod]
[Obsolete("Obsolete")]
public void MoveByOffsetFromTopLeftOfElement ()
{
driver . Url = "https://selenium.dev/selenium/web/mouse_interaction.html" ;
IWebElement tracker = driver . FindElement ( By . Id ( "mouse-tracker" ));
new Actions ( driver )
. MoveToElement ( tracker , 8 , 0 )
. Perform ();
string [] result = driver . FindElement ( By . Id ( "relative-location" )). Text . Split ( ", " );
Assert . IsTrue ( Math . Abs ( int . Parse ( result [ 0 ]) - 100 - 8 ) < 2 );
}
[TestMethod]
public void MoveByOffsetFromCenterOfElement ()
{
driver . Url = "https://selenium.dev/selenium/web/mouse_interaction.html" ;
IWebElement tracker = driver . FindElement ( By . Id ( "mouse-tracker" ));
new Actions ( driver )
. MoveToElement ( tracker , 8 , 0 )
. Perform ();
string [] result = driver . FindElement ( By . Id ( "relative-location" )). Text . Split ( ", " );
Assert . IsTrue ( Math . Abs ( int . Parse ( result [ 0 ]) - 100 - 8 ) < 2 );
}
[TestMethod]
public void MoveByOffsetFromViewport ()
{
driver . Url = "https://selenium.dev/selenium/web/mouse_interaction.html" ;
ActionBuilder actionBuilder = new ActionBuilder ();
PointerInputDevice mouse = new PointerInputDevice ( PointerKind . Mouse , "default mouse" );
actionBuilder . AddAction ( mouse . CreatePointerMove ( CoordinateOrigin . Viewport ,
8 , 0 , TimeSpan . Zero ));
(( IActionExecutor ) driver ). PerformActions ( actionBuilder . ToActionSequenceList ());
string [] result = driver . FindElement ( By . Id ( "absolute-location" )). Text . Split ( ", " );
Assert . IsTrue ( Math . Abs ( int . Parse ( result [ 0 ]) - 8 ) < 2 );
}
[TestMethod]
public void MoveByOffsetFromCurrentPointerLocation ()
{
driver . Url = "https://selenium.dev/selenium/web/mouse_interaction.html" ;
ActionBuilder actionBuilder = new ActionBuilder ();
PointerInputDevice mouse = new PointerInputDevice ( PointerKind . Mouse , "default mouse" );
actionBuilder . AddAction ( mouse . CreatePointerMove ( CoordinateOrigin . Viewport ,
8 , 12 , TimeSpan . Zero ));
(( IActionExecutor ) driver ). PerformActions ( actionBuilder . ToActionSequenceList ());
new Actions ( driver )
. MoveByOffset ( 13 , 15 )
. Perform ();
string [] result = driver . FindElement ( By . Id ( "absolute-location" )). Text . Split ( ", " );
Assert . IsTrue ( Math . Abs ( int . Parse ( result [ 0 ]) - 8 - 13 ) < 2 );
Assert . IsTrue ( Math . Abs ( int . Parse ( result [ 1 ]) - 12 - 15 ) < 2 );
}
[TestMethod]
public void DragToElement ()
{
driver . Url = "https://selenium.dev/selenium/web/mouse_interaction.html" ;
IWebElement draggable = driver . FindElement ( By . Id ( "draggable" ));
IWebElement droppable = driver . FindElement ( By . Id ( "droppable" ));
new Actions ( driver )
. DragAndDrop ( draggable , droppable )
. Perform ();
Assert . AreEqual ( "dropped" , driver . FindElement ( By . Id ( "drop-status" )). Text );
}
[TestMethod]
public void DragByOffset ()
{
driver . Url = "https://selenium.dev/selenium/web/mouse_interaction.html" ;
IWebElement draggable = driver . FindElement ( By . Id ( "draggable" ));
Point start = draggable . Location ;
Point finish = driver . FindElement ( By . Id ( "droppable" )). Location ;
new Actions ( driver )
. DragAndDropToOffset ( draggable , finish . X - start . X , finish . Y - start . Y )
. Perform ();
Assert . AreEqual ( "dropped" , driver . FindElement ( By . Id ( "drop-status" )). Text );
}
}
}
hoverable = driver . find_element ( id : 'hover' )
driver . action
. move_to ( hoverable )
. perform
Show full example # frozen_string_literal: true
require 'spec_helper'
RSpec . describe 'Mouse' do
let ( :driver ) { start_session }
it 'click and hold' do
driver . get 'https://www.selenium.dev/selenium/web/mouse_interaction.html'
clickable = driver . find_element ( id : 'clickable' )
driver . action
. click_and_hold ( clickable )
. perform
expect ( driver . find_element ( id : 'click-status' ) . text ) . to eq 'focused'
end
it 'click and release' do
driver . get 'https://www.selenium.dev/selenium/web/mouse_interaction.html'
clickable = driver . find_element ( id : 'click' )
driver . action
. click ( clickable )
. perform
expect ( driver . current_url ) . to include 'resultPage.html'
end
describe 'alternate button clicks' do
it 'right click' do
driver . get 'https://www.selenium.dev/selenium/web/mouse_interaction.html'
clickable = driver . find_element ( id : 'clickable' )
driver . action
. context_click ( clickable )
. perform
expect ( driver . find_element ( id : 'click-status' ) . text ) . to eq 'context-clicked'
end
it 'back click' do
driver . get 'https://www.selenium.dev/selenium/web/mouse_interaction.html'
driver . find_element ( id : 'click' ) . click
expect ( driver . title ) . to eq ( 'We Arrive Here' )
driver . action
. pointer_down ( :back )
. pointer_up ( :back )
. perform
expect ( driver . title ) . to eq ( 'BasicMouseInterfaceTest' )
end
it 'forward click' do
driver . get 'https://www.selenium.dev/selenium/web/mouse_interaction.html'
driver . find_element ( id : 'click' ) . click
driver . navigate . back
expect ( driver . title ) . to eq ( 'BasicMouseInterfaceTest' )
driver . action
. pointer_down ( :forward )
. pointer_up ( :forward )
. perform
expect ( driver . title ) . to eq ( 'We Arrive Here' )
end
end
it 'double click' do
driver . get 'https://www.selenium.dev/selenium/web/mouse_interaction.html'
clickable = driver . find_element ( id : 'clickable' )
driver . action
. double_click ( clickable )
. perform
expect ( driver . find_element ( id : 'click-status' ) . text ) . to eq 'double-clicked'
end
it 'hovers' do
driver . get 'https://www.selenium.dev/selenium/web/mouse_interaction.html'
hoverable = driver . find_element ( id : 'hover' )
driver . action
. move_to ( hoverable )
. perform
expect ( driver . find_element ( id : 'move-status' ) . text ) . to eq 'hovered'
end
describe 'move by offset' do
it 'offset from element' do
driver . get 'https://www.selenium.dev/selenium/web/mouse_interaction.html'
driver . action . scroll_to ( driver . find_element ( id : 'bottom' )) . perform
mouse_tracker = driver . find_element ( id : 'mouse-tracker' )
driver . action
. move_to ( mouse_tracker , 8 , 11 )
. perform
rect = mouse_tracker . rect
center_x = rect . width / 2
center_y = rect . height / 2
x_coord , y_coord = driver . find_element ( id : 'relative-location' ) . text . split ( ',' ) . map ( & :to_i )
expect ( x_coord ) . to be_within ( 1 ) . of ( center_x + 8 )
expect ( y_coord ) . to be_within ( 1 ) . of ( center_y + 11 )
end
it 'offset from viewport' do
driver . get 'https://www.selenium.dev/selenium/web/mouse_interaction.html'
driver . action
. move_to_location ( 8 , 12 )
. perform
x_coord , y_coord = driver . find_element ( id : 'absolute-location' ) . text . split ( ',' ) . map ( & :to_i )
expect ( x_coord ) . to be_within ( 1 ) . of ( 8 )
expect ( y_coord ) . to be_within ( 1 ) . of ( 12 )
end
it 'offset from current pointer location' do
driver . get 'https://www.selenium.dev/selenium/web/mouse_interaction.html'
driver . action . move_to_location ( 8 , 11 ) . perform
driver . action
. move_by ( 13 , 15 )
. perform
x_coord , y_coord = driver . find_element ( id : 'absolute-location' ) . text . split ( ',' ) . map ( & :to_i )
expect ( x_coord ) . to be_within ( 1 ) . of ( 8 + 13 )
expect ( y_coord ) . to be_within ( 1 ) . of ( 11 + 15 )
end
end
it 'drags to another element' do
driver . get 'https://www.selenium.dev/selenium/web/mouse_interaction.html'
draggable = driver . find_element ( id : 'draggable' )
droppable = driver . find_element ( id : 'droppable' )
driver . action
. drag_and_drop ( draggable , droppable )
. perform
expect ( driver . find_element ( id : 'drop-status' ) . text ) . to include ( 'dropped' )
end
it 'drags by an offset' do
driver . get 'https://www.selenium.dev/selenium/web/mouse_interaction.html'
draggable = driver . find_element ( id : 'draggable' )
start = draggable . rect
finish = driver . find_element ( id : 'droppable' ) . rect
driver . action
. drag_and_drop_by ( draggable , finish . x - start . x , finish . y - start . y )
. perform
expect ( driver . find_element ( id : 'drop-status' ) . text ) . to include ( 'dropped' )
end
end
const hoverable = driver . findElement ( By . id ( "hover" ));
const actions = driver . actions ({ async : true });
await actions . move ({ origin : hoverable }). perform ();
Show full example const { By , Builder } = require ( 'selenium-webdriver' );
const assert = require ( "assert" );
describe ( 'Move to element' , function () {
let driver ;
before ( async function () {
driver = new Builder (). forBrowser ( 'chrome' ). build ();
});
after ( async () => await driver . quit ());
it ( 'Mouse move into an element' , async function () {
await driver . get ( 'https://www.selenium.dev/selenium/web/mouse_interaction.html' );
const hoverable = driver . findElement ( By . id ( "hover" ));
const actions = driver . actions ({ async : true });
await actions . move ({ origin : hoverable }). perform ();
const status = await driver . findElement ( By . id ( 'move-status' )). getText ();
assert . deepStrictEqual ( status , `hovered` )
});
});
val hoverable = driver . findElement ( By . id ( "hover" ))
Actions ( driver )
. moveToElement ( hoverable )
. perform ()
Show full example 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.Rectangle
import org.openqa.selenium.WebElement
import org.openqa.selenium.interactions.Actions
import org.openqa.selenium.interactions.PointerInput
import org.openqa.selenium.interactions.Sequence
import org.openqa.selenium.remote.RemoteWebDriver
import java.time.Duration
import java.util.Collections
class MouseTest : BaseTest () {
@Test
fun clickAndHold () {
driver . get ( "https://www.selenium.dev/selenium/web/mouse_interaction.html" )
val clickable = driver . findElement ( By . id ( "clickable" ))
Actions ( driver )
. clickAndHold ( clickable )
. perform ()
Assertions . assertEquals ( "focused" , driver . findElement ( By . id ( "click-status" )). getText ())
}
@Test
fun clickAndRelease () {
driver . get ( "https://www.selenium.dev/selenium/web/mouse_interaction.html" )
val clickable = driver . findElement ( By . id ( "click" ))
Actions ( driver )
. click ( clickable )
. perform ()
Assertions . assertTrue ( driver . getCurrentUrl () !! . contains ( "resultPage.html" ))
}
@Test
fun rightClick () {
driver . get ( "https://www.selenium.dev/selenium/web/mouse_interaction.html" )
val clickable = driver . findElement ( By . id ( "clickable" ))
Actions ( driver )
. contextClick ( clickable )
. perform ()
Assertions . assertEquals ( "context-clicked" , driver . findElement ( By . id ( "click-status" )). getText ())
}
@Test
fun backClick () {
driver . get ( "https://www.selenium.dev/selenium/web/mouse_interaction.html" )
driver . findElement ( By . id ( "click" )). click ()
Assertions . assertEquals ( driver . getTitle (), "We Arrive Here" )
val mouse = PointerInput ( PointerInput . Kind . MOUSE , "default mouse" )
val actions = Sequence ( mouse , 0 )
. addAction ( mouse . createPointerDown ( PointerInput . MouseButton . BACK . asArg ()))
. addAction ( mouse . createPointerUp ( PointerInput . MouseButton . BACK . asArg ()))
( driver as RemoteWebDriver ). perform ( Collections . singletonList ( actions ))
Assertions . assertEquals ( "BasicMouseInterfaceTest" , driver . getTitle ())
}
@Test
fun forwardClick () {
driver . get ( "https://www.selenium.dev/selenium/web/mouse_interaction.html" )
driver . findElement ( By . id ( "click" )). click ()
driver . navigate (). back ()
Assertions . assertEquals ( driver . getTitle (), "BasicMouseInterfaceTest" )
val mouse = PointerInput ( PointerInput . Kind . MOUSE , "default mouse" )
val actions = Sequence ( mouse , 0 )
. addAction ( mouse . createPointerDown ( PointerInput . MouseButton . FORWARD . asArg ()))
. addAction ( mouse . createPointerUp ( PointerInput . MouseButton . FORWARD . asArg ()))
( driver as RemoteWebDriver ). perform ( Collections . singletonList ( actions ))
Assertions . assertEquals ( "We Arrive Here" , driver . getTitle ())
}
@Test
fun doubleClick () {
driver . get ( "https://www.selenium.dev/selenium/web/mouse_interaction.html" )
val clickable = driver . findElement ( By . id ( "clickable" ))
Actions ( driver )
. doubleClick ( clickable )
. perform ()
Assertions . assertEquals ( "double-clicked" , driver . findElement ( By . id ( "click-status" )). getText ())
}
@Test
fun hovers () {
driver . get ( "https://www.selenium.dev/selenium/web/mouse_interaction.html" )
val hoverable = driver . findElement ( By . id ( "hover" ))
Actions ( driver )
. moveToElement ( hoverable )
. perform ()
Assertions . assertEquals ( "hovered" , driver . findElement ( By . id ( "move-status" )). getText ())
}
@Test
fun moveByOffsetFromElement () {
driver . get ( "https://www.selenium.dev/selenium/web/mouse_interaction.html" )
driver . manage (). window (). fullscreen ()
val tracker = driver . findElement ( By . id ( "mouse-tracker" ))
Actions ( driver )
. moveToElement ( tracker , 8 , 0 )
. perform ()
val result = driver . findElement ( By . id ( "relative-location" )). getText (). split ( ", " )
Assertions . assertTrue ( Math . abs ( Integer . parseInt ( result [ 0 ]) - 100 - 8 ) < 2 )
}
@Test
fun moveByOffsetFromViewport () {
driver . get ( "https://www.selenium.dev/selenium/web/mouse_interaction.html" )
val mouse = PointerInput ( PointerInput . Kind . MOUSE , "default mouse" )
val actions = Sequence ( mouse , 0 )
. addAction ( mouse . createPointerMove ( Duration . ZERO , PointerInput . Origin . viewport (), 8 , 12 ))
( driver as RemoteWebDriver ). perform ( Collections . singletonList ( actions ))
val result = driver . findElement ( By . id ( "absolute-location" )). getText (). split ( ", " )
Assertions . assertTrue ( Math . abs ( Integer . parseInt ( result [ 0 ]) - 8 ) < 2 )
Assertions . assertTrue ( Math . abs ( Integer . parseInt ( result [ 1 ]) - 12 ) < 2 )
}
@Test
fun moveByOffsetFromCurrentPointer () {
driver . get ( "https://www.selenium.dev/selenium/web/mouse_interaction.html" )
val mouse = PointerInput ( PointerInput . Kind . MOUSE , "default mouse" )
val actions = Sequence ( mouse , 0 )
. addAction ( mouse . createPointerMove ( Duration . ZERO , PointerInput . Origin . viewport (), 8 , 11 ))
( driver as RemoteWebDriver ). perform ( Collections . singletonList ( actions ))
Actions ( driver )
. moveByOffset ( 13 , 15 )
. perform ()
val result = driver . findElement ( By . id ( "absolute-location" )). getText (). split ( ", " )
Assertions . assertTrue ( Math . abs ( Integer . parseInt ( result [ 0 ]) - 8 - 13 ) < 2 )
Assertions . assertTrue ( Math . abs ( Integer . parseInt ( result [ 1 ]) - 11 - 15 ) < 2 )
}
@Test
fun dragsToElement () {
driver . get ( "https://www.selenium.dev/selenium/web/mouse_interaction.html" )
val draggable = driver . findElement ( By . id ( "draggable" ))
val droppable = driver . findElement ( By . id ( "droppable" ))
Actions ( driver )
. dragAndDrop ( draggable , droppable )
. perform ()
Assertions . assertEquals ( "dropped" , driver . findElement ( By . id ( "drop-status" )). getText ())
}
@Test
fun dragsByOffset () {
driver . get ( "https://www.selenium.dev/selenium/web/mouse_interaction.html" )
val draggable = driver . findElement ( By . id ( "draggable" ))
val start = draggable . getRect ()
val finish = driver . findElement ( By . id ( "droppable" )). getRect ()
Actions ( driver )
. dragAndDropBy ( draggable , finish . getX () - start . getX (), finish . getY () - start . getY ())
. perform ()
Assertions . assertEquals ( "dropped" , driver . findElement ( By . id ( "drop-status" )). getText ())
}
}
Mover por Deslocamento Esses métodos primeiro movem o mouse para a origem designada e, em seguida, pelo número de pixels especificado no deslocamento fornecido. É importante observar que a posição do mouse deve estar dentro da janela de visualização (viewport) ou, caso contrário, o comando resultará em erro.
Deslocamento a partir do Elemento Este método move o mouse para o ponto central do elemento visível na tela e, em seguida, move o mouse pelo deslocamento fornecido.
Java
Python
CSharp
Ruby
JavaScript
Kotlin WebElement tracker = driver . findElement ( By . id ( "mouse-tracker" ));
new Actions ( driver )
. moveToElement ( tracker , 8 , 0 )
. perform ();
Show full example 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.Rectangle ;
import org.openqa.selenium.WebElement ;
import org.openqa.selenium.interactions.Actions ;
import org.openqa.selenium.interactions.PointerInput ;
import org.openqa.selenium.interactions.Sequence ;
import org.openqa.selenium.remote.RemoteWebDriver ;
import java.time.Duration ;
import java.util.Collections ;
public class MouseTest extends BaseChromeTest {
@Test
public void clickAndHold () {
driver . get ( "https://www.selenium.dev/selenium/web/mouse_interaction.html" );
WebElement clickable = driver . findElement ( By . id ( "clickable" ));
new Actions ( driver )
. clickAndHold ( clickable )
. perform ();
Assertions . assertEquals ( "focused" , driver . findElement ( By . id ( "click-status" )). getText ());
}
@Test
public void clickAndRelease () {
driver . get ( "https://www.selenium.dev/selenium/web/mouse_interaction.html" );
WebElement clickable = driver . findElement ( By . id ( "click" ));
new Actions ( driver )
. click ( clickable )
. perform ();
Assertions . assertTrue ( driver . getCurrentUrl (). contains ( "resultPage.html" ));
}
@Test
public void rightClick () {
driver . get ( "https://www.selenium.dev/selenium/web/mouse_interaction.html" );
WebElement clickable = driver . findElement ( By . id ( "clickable" ));
new Actions ( driver )
. contextClick ( clickable )
. perform ();
Assertions . assertEquals ( "context-clicked" , driver . findElement ( By . id ( "click-status" )). getText ());
}
@Test
public void backClick () {
driver . get ( "https://www.selenium.dev/selenium/web/mouse_interaction.html" );
driver . findElement ( By . id ( "click" )). click ();
Assertions . assertEquals ( driver . getTitle (), "We Arrive Here" );
PointerInput mouse = new PointerInput ( PointerInput . Kind . MOUSE , "default mouse" );
Sequence actions = new Sequence ( mouse , 0 )
. addAction ( mouse . createPointerDown ( PointerInput . MouseButton . BACK . asArg ()))
. addAction ( mouse . createPointerUp ( PointerInput . MouseButton . BACK . asArg ()));
(( RemoteWebDriver ) driver ). perform ( Collections . singletonList ( actions ));
Assertions . assertEquals ( "BasicMouseInterfaceTest" , driver . getTitle ());
}
@Test
public void forwardClick () {
driver . get ( "https://www.selenium.dev/selenium/web/mouse_interaction.html" );
driver . findElement ( By . id ( "click" )). click ();
driver . navigate (). back ();
Assertions . assertEquals ( driver . getTitle (), "BasicMouseInterfaceTest" );
PointerInput mouse = new PointerInput ( PointerInput . Kind . MOUSE , "default mouse" );
Sequence actions = new Sequence ( mouse , 0 )
. addAction ( mouse . createPointerDown ( PointerInput . MouseButton . FORWARD . asArg ()))
. addAction ( mouse . createPointerUp ( PointerInput . MouseButton . FORWARD . asArg ()));
(( RemoteWebDriver ) driver ). perform ( Collections . singletonList ( actions ));
Assertions . assertEquals ( "We Arrive Here" , driver . getTitle ());
}
@Test
public void doubleClick () {
driver . get ( "https://www.selenium.dev/selenium/web/mouse_interaction.html" );
WebElement clickable = driver . findElement ( By . id ( "clickable" ));
new Actions ( driver )
. doubleClick ( clickable )
. perform ();
Assertions . assertEquals ( "double-clicked" , driver . findElement ( By . id ( "click-status" )). getText ());
}
@Test
public void hovers () {
driver . get ( "https://www.selenium.dev/selenium/web/mouse_interaction.html" );
WebElement hoverable = driver . findElement ( By . id ( "hover" ));
new Actions ( driver )
. moveToElement ( hoverable )
. perform ();
Assertions . assertEquals ( "hovered" , driver . findElement ( By . id ( "move-status" )). getText ());
}
@Test
public void moveByOffsetFromElement () {
driver . get ( "https://www.selenium.dev/selenium/web/mouse_interaction.html" );
driver . manage (). window (). fullscreen ();
WebElement tracker = driver . findElement ( By . id ( "mouse-tracker" ));
new Actions ( driver )
. moveToElement ( tracker , 8 , 0 )
. perform ();
String [] result = driver . findElement ( By . id ( "relative-location" )). getText (). split ( ", " );
Assertions . assertTrue ( Math . abs ( Integer . parseInt ( result [ 0 ] ) - 100 - 8 ) < 2 );
}
@Test
public void moveByOffsetFromViewport () {
driver . get ( "https://www.selenium.dev/selenium/web/mouse_interaction.html" );
PointerInput mouse = new PointerInput ( PointerInput . Kind . MOUSE , "default mouse" );
Sequence actions = new Sequence ( mouse , 0 )
. addAction ( mouse . createPointerMove ( Duration . ZERO , PointerInput . Origin . viewport (), 8 , 12 ));
(( RemoteWebDriver ) driver ). perform ( Collections . singletonList ( actions ));
String [] result = driver . findElement ( By . id ( "absolute-location" )). getText (). split ( ", " );
Assertions . assertTrue ( Math . abs ( Integer . parseInt ( result [ 0 ] ) - 8 ) < 2 );
Assertions . assertTrue ( Math . abs ( Integer . parseInt ( result [ 1 ] ) - 12 ) < 2 );
}
@Test
public void moveByOffsetFromCurrentPointer () {
driver . get ( "https://www.selenium.dev/selenium/web/mouse_interaction.html" );
PointerInput mouse = new PointerInput ( PointerInput . Kind . MOUSE , "default mouse" );
Sequence actions = new Sequence ( mouse , 0 )
. addAction ( mouse . createPointerMove ( Duration . ZERO , PointerInput . Origin . viewport (), 8 , 11 ));
(( RemoteWebDriver ) driver ). perform ( Collections . singletonList ( actions ));
new Actions ( driver )
. moveByOffset ( 13 , 15 )
. perform ();
String [] result = driver . findElement ( By . id ( "absolute-location" )). getText (). split ( ", " );
Assertions . assertTrue ( Math . abs ( Integer . parseInt ( result [ 0 ] ) - 8 - 13 ) < 2 );
Assertions . assertTrue ( Math . abs ( Integer . parseInt ( result [ 1 ] ) - 11 - 15 ) < 2 );
}
@Test
public void dragsToElement () {
driver . get ( "https://www.selenium.dev/selenium/web/mouse_interaction.html" );
WebElement draggable = driver . findElement ( By . id ( "draggable" ));
WebElement droppable = driver . findElement ( By . id ( "droppable" ));
new Actions ( driver )
. dragAndDrop ( draggable , droppable )
. perform ();
Assertions . assertEquals ( "dropped" , driver . findElement ( By . id ( "drop-status" )). getText ());
}
@Test
public void dragsByOffset () {
driver . get ( "https://www.selenium.dev/selenium/web/mouse_interaction.html" );
WebElement draggable = driver . findElement ( By . id ( "draggable" ));
Rectangle start = draggable . getRect ();
Rectangle finish = driver . findElement ( By . id ( "droppable" )). getRect ();
new Actions ( driver )
. dragAndDropBy ( draggable , finish . getX () - start . getX (), finish . getY () - start . getY ())
. perform ();
Assertions . assertEquals ( "dropped" , driver . findElement ( By . id ( "drop-status" )). getText ());
}
}
mouse_tracker = driver . find_element ( By . ID , "mouse-tracker" )
ActionChains ( driver ) \
. move_to_element_with_offset ( mouse_tracker , 8 , 0 ) \
. perform ()
Show full example import pytest
from time import sleep
from selenium.webdriver import ActionChains
from selenium.webdriver.common.actions.action_builder import ActionBuilder
from selenium.webdriver.common.actions.mouse_button import MouseButton
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
def test_click_and_hold ( driver ):
driver . get ( 'https://selenium.dev/selenium/web/mouse_interaction.html' )
clickable = driver . find_element ( By . ID , "clickable" )
ActionChains ( driver ) \
. click_and_hold ( clickable ) \
. perform ()
sleep ( 0.5 )
assert driver . find_element ( By . ID , "click-status" ) . text == "focused"
def test_click_and_release ( driver ):
driver . get ( 'https://selenium.dev/selenium/web/mouse_interaction.html' )
clickable = driver . find_element ( By . ID , "click" )
ActionChains ( driver ) \
. click ( clickable ) \
. perform ()
assert "resultPage.html" in driver . current_url
def test_right_click ( driver ):
driver . get ( 'https://selenium.dev/selenium/web/mouse_interaction.html' )
clickable = driver . find_element ( By . ID , "clickable" )
ActionChains ( driver ) \
. context_click ( clickable ) \
. perform ()
sleep ( 0.5 )
assert driver . find_element ( By . ID , "click-status" ) . text == "context-clicked"
def test_back_click_ab ( driver ):
driver . get ( 'https://selenium.dev/selenium/web/mouse_interaction.html' )
driver . find_element ( By . ID , "click" ) . click ()
assert driver . title == "We Arrive Here"
action = ActionBuilder ( driver )
action . pointer_action . pointer_down ( MouseButton . BACK )
action . pointer_action . pointer_up ( MouseButton . BACK )
action . perform ()
assert driver . title == "BasicMouseInterfaceTest"
def test_forward_click_ab ( driver ):
driver . get ( 'https://selenium.dev/selenium/web/mouse_interaction.html' )
driver . find_element ( By . ID , "click" ) . click ()
driver . back ()
assert driver . title == "BasicMouseInterfaceTest"
action = ActionBuilder ( driver )
action . pointer_action . pointer_down ( MouseButton . FORWARD )
action . pointer_action . pointer_up ( MouseButton . FORWARD )
action . perform ()
assert driver . title == "We Arrive Here"
def test_double_click ( driver ):
driver . get ( 'https://selenium.dev/selenium/web/mouse_interaction.html' )
clickable = driver . find_element ( By . ID , "clickable" )
ActionChains ( driver ) \
. double_click ( clickable ) \
. perform ()
assert driver . find_element ( By . ID , "click-status" ) . text == "double-clicked"
def test_hover ( driver ):
driver . get ( 'https://selenium.dev/selenium/web/mouse_interaction.html' )
hoverable = driver . find_element ( By . ID , "hover" )
ActionChains ( driver ) \
. move_to_element ( hoverable ) \
. perform ()
assert driver . find_element ( By . ID , "move-status" ) . text == "hovered"
def test_move_by_offset_from_element ( driver ):
driver . get ( 'https://selenium.dev/selenium/web/mouse_interaction.html' )
mouse_tracker = driver . find_element ( By . ID , "mouse-tracker" )
ActionChains ( driver ) \
. move_to_element_with_offset ( mouse_tracker , 8 , 0 ) \
. perform ()
coordinates = driver . find_element ( By . ID , "relative-location" ) . text . split ( ", " )
assert abs ( int ( coordinates [ 0 ]) - 100 - 8 ) < 2
def test_move_by_offset_from_viewport_origin_ab ( driver ):
driver . get ( 'https://selenium.dev/selenium/web/mouse_interaction.html' )
WebDriverWait ( driver , 10 ) . until ( EC . presence_of_element_located (( By . ID , "absolute-location" )))
action = ActionBuilder ( driver )
action . pointer_action . move_to_location ( 8 , 0 )
action . perform ()
coordinates = driver . find_element ( By . ID , "absolute-location" ) . text . split ( ", " )
assert abs ( int ( coordinates [ 0 ]) - 8 ) < 2
def test_move_by_offset_from_current_pointer_ab ( driver ):
driver . get ( 'https://selenium.dev/selenium/web/mouse_interaction.html' )
action = ActionBuilder ( driver )
action . pointer_action . move_to_location ( 6 , 3 )
action . perform ()
ActionChains ( driver ) \
. move_by_offset ( 13 , 15 ) \
. perform ()
coordinates = driver . find_element ( By . ID , "absolute-location" ) . text . split ( ", " )
assert abs ( int ( coordinates [ 0 ]) - 6 - 13 ) < 2
assert abs ( int ( coordinates [ 1 ]) - 3 - 15 ) < 2
def test_drag_and_drop_onto_element ( driver ):
driver . get ( 'https://selenium.dev/selenium/web/mouse_interaction.html' )
draggable = driver . find_element ( By . ID , "draggable" )
droppable = driver . find_element ( By . ID , "droppable" )
ActionChains ( driver ) \
. drag_and_drop ( draggable , droppable ) \
. perform ()
assert driver . find_element ( By . ID , "drop-status" ) . text == "dropped"
def test_drag_and_drop_by_offset ( driver ):
driver . get ( 'https://selenium.dev/selenium/web/mouse_interaction.html' )
draggable = driver . find_element ( By . ID , "draggable" )
start = draggable . location
finish = driver . find_element ( By . ID , "droppable" ) . location
ActionChains ( driver ) \
. drag_and_drop_by_offset ( draggable , finish [ 'x' ] - start [ 'x' ], finish [ 'y' ] - start [ 'y' ]) \
. perform ()
assert driver . find_element ( By . ID , "drop-status" ) . text == "dropped"
IWebElement tracker = driver . FindElement ( By . Id ( "mouse-tracker" ));
new Actions ( driver )
. MoveToElement ( tracker , 8 , 0 )
. Perform ();
Show full example using System ;
using System.Drawing ;
using Microsoft.VisualStudio.TestTools.UnitTesting ;
using OpenQA.Selenium ;
using OpenQA.Selenium.Interactions ;
namespace SeleniumDocs.ActionsAPI
{
[TestClass]
public class MouseTest : BaseChromeTest
{
[TestMethod]
public void ClickAndHold ()
{
driver . Url = "https://selenium.dev/selenium/web/mouse_interaction.html" ;
IWebElement clickable = driver . FindElement ( By . Id ( "clickable" ));
new Actions ( driver )
. ClickAndHold ( clickable )
. Perform ();
Assert . AreEqual ( "focused" , driver . FindElement ( By . Id ( "click-status" )). Text );
}
[TestMethod]
public void ClickAndRelease ()
{
driver . Url = "https://selenium.dev/selenium/web/mouse_interaction.html" ;
IWebElement clickable = driver . FindElement ( By . Id ( "click" ));
new Actions ( driver )
. Click ( clickable )
. Perform ();
Assert . IsTrue ( driver . Url . Contains ( "resultPage.html" ));
}
[TestMethod]
public void RightClick ()
{
driver . Url = "https://selenium.dev/selenium/web/mouse_interaction.html" ;
IWebElement clickable = driver . FindElement ( By . Id ( "clickable" ));
new Actions ( driver )
. ContextClick ( clickable )
. Perform ();
Assert . AreEqual ( "context-clicked" , driver . FindElement ( By . Id ( "click-status" )). Text );
}
[TestMethod]
public void BackClick ()
{
driver . Url = "https://selenium.dev/selenium/web/mouse_interaction.html" ;
driver . FindElement ( By . Id ( "click" )). Click ();
Assert . AreEqual ( "We Arrive Here" , driver . Title );
ActionBuilder actionBuilder = new ActionBuilder ();
PointerInputDevice mouse = new PointerInputDevice ( PointerKind . Mouse , "default mouse" );
actionBuilder . AddAction ( mouse . CreatePointerDown ( MouseButton . Back ));
actionBuilder . AddAction ( mouse . CreatePointerUp ( MouseButton . Back ));
(( IActionExecutor ) driver ). PerformActions ( actionBuilder . ToActionSequenceList ());
Assert . AreEqual ( "BasicMouseInterfaceTest" , driver . Title );
}
[TestMethod]
public void ForwardClick ()
{
driver . Url = "https://selenium.dev/selenium/web/mouse_interaction.html" ;
driver . FindElement ( By . Id ( "click" )). Click ();
driver . Navigate (). Back ();
Assert . AreEqual ( "BasicMouseInterfaceTest" , driver . Title );
ActionBuilder actionBuilder = new ActionBuilder ();
PointerInputDevice mouse = new PointerInputDevice ( PointerKind . Mouse , "default mouse" );
actionBuilder . AddAction ( mouse . CreatePointerDown ( MouseButton . Forward ));
actionBuilder . AddAction ( mouse . CreatePointerUp ( MouseButton . Forward ));
(( IActionExecutor ) driver ). PerformActions ( actionBuilder . ToActionSequenceList ());
Assert . AreEqual ( "We Arrive Here" , driver . Title );
}
[TestMethod]
public void DoubleClick ()
{
driver . Url = "https://selenium.dev/selenium/web/mouse_interaction.html" ;
IWebElement clickable = driver . FindElement ( By . Id ( "clickable" ));
new Actions ( driver )
. DoubleClick ( clickable )
. Perform ();
Assert . AreEqual ( "double-clicked" , driver . FindElement ( By . Id ( "click-status" )). Text );
}
[TestMethod]
public void Hovers ()
{
driver . Url = "https://selenium.dev/selenium/web/mouse_interaction.html" ;
IWebElement hoverable = driver . FindElement ( By . Id ( "hover" ));
new Actions ( driver )
. MoveToElement ( hoverable )
. Perform ();
Assert . AreEqual ( "hovered" , driver . FindElement ( By . Id ( "move-status" )). Text );
}
[TestMethod]
[Obsolete("Obsolete")]
public void MoveByOffsetFromTopLeftOfElement ()
{
driver . Url = "https://selenium.dev/selenium/web/mouse_interaction.html" ;
IWebElement tracker = driver . FindElement ( By . Id ( "mouse-tracker" ));
new Actions ( driver )
. MoveToElement ( tracker , 8 , 0 )
. Perform ();
string [] result = driver . FindElement ( By . Id ( "relative-location" )). Text . Split ( ", " );
Assert . IsTrue ( Math . Abs ( int . Parse ( result [ 0 ]) - 100 - 8 ) < 2 );
}
[TestMethod]
public void MoveByOffsetFromCenterOfElement ()
{
driver . Url = "https://selenium.dev/selenium/web/mouse_interaction.html" ;
IWebElement tracker = driver . FindElement ( By . Id ( "mouse-tracker" ));
new Actions ( driver )
. MoveToElement ( tracker , 8 , 0 )
. Perform ();
string [] result = driver . FindElement ( By . Id ( "relative-location" )). Text . Split ( ", " );
Assert . IsTrue ( Math . Abs ( int . Parse ( result [ 0 ]) - 100 - 8 ) < 2 );
}
[TestMethod]
public void MoveByOffsetFromViewport ()
{
driver . Url = "https://selenium.dev/selenium/web/mouse_interaction.html" ;
ActionBuilder actionBuilder = new ActionBuilder ();
PointerInputDevice mouse = new PointerInputDevice ( PointerKind . Mouse , "default mouse" );
actionBuilder . AddAction ( mouse . CreatePointerMove ( CoordinateOrigin . Viewport ,
8 , 0 , TimeSpan . Zero ));
(( IActionExecutor ) driver ). PerformActions ( actionBuilder . ToActionSequenceList ());
string [] result = driver . FindElement ( By . Id ( "absolute-location" )). Text . Split ( ", " );
Assert . IsTrue ( Math . Abs ( int . Parse ( result [ 0 ]) - 8 ) < 2 );
}
[TestMethod]
public void MoveByOffsetFromCurrentPointerLocation ()
{
driver . Url = "https://selenium.dev/selenium/web/mouse_interaction.html" ;
ActionBuilder actionBuilder = new ActionBuilder ();
PointerInputDevice mouse = new PointerInputDevice ( PointerKind . Mouse , "default mouse" );
actionBuilder . AddAction ( mouse . CreatePointerMove ( CoordinateOrigin . Viewport ,
8 , 12 , TimeSpan . Zero ));
(( IActionExecutor ) driver ). PerformActions ( actionBuilder . ToActionSequenceList ());
new Actions ( driver )
. MoveByOffset ( 13 , 15 )
. Perform ();
string [] result = driver . FindElement ( By . Id ( "absolute-location" )). Text . Split ( ", " );
Assert . IsTrue ( Math . Abs ( int . Parse ( result [ 0 ]) - 8 - 13 ) < 2 );
Assert . IsTrue ( Math . Abs ( int . Parse ( result [ 1 ]) - 12 - 15 ) < 2 );
}
[TestMethod]
public void DragToElement ()
{
driver . Url = "https://selenium.dev/selenium/web/mouse_interaction.html" ;
IWebElement draggable = driver . FindElement ( By . Id ( "draggable" ));
IWebElement droppable = driver . FindElement ( By . Id ( "droppable" ));
new Actions ( driver )
. DragAndDrop ( draggable , droppable )
. Perform ();
Assert . AreEqual ( "dropped" , driver . FindElement ( By . Id ( "drop-status" )). Text );
}
[TestMethod]
public void DragByOffset ()
{
driver . Url = "https://selenium.dev/selenium/web/mouse_interaction.html" ;
IWebElement draggable = driver . FindElement ( By . Id ( "draggable" ));
Point start = draggable . Location ;
Point finish = driver . FindElement ( By . Id ( "droppable" )). Location ;
new Actions ( driver )
. DragAndDropToOffset ( draggable , finish . X - start . X , finish . Y - start . Y )
. Perform ();
Assert . AreEqual ( "dropped" , driver . FindElement ( By . Id ( "drop-status" )). Text );
}
}
}
mouse_tracker = driver . find_element ( id : 'mouse-tracker' )
driver . action
. move_to ( mouse_tracker , 8 , 11 )
. perform
Show full example # frozen_string_literal: true
require 'spec_helper'
RSpec . describe 'Mouse' do
let ( :driver ) { start_session }
it 'click and hold' do
driver . get 'https://www.selenium.dev/selenium/web/mouse_interaction.html'
clickable = driver . find_element ( id : 'clickable' )
driver . action
. click_and_hold ( clickable )
. perform
expect ( driver . find_element ( id : 'click-status' ) . text ) . to eq 'focused'
end
it 'click and release' do
driver . get 'https://www.selenium.dev/selenium/web/mouse_interaction.html'
clickable = driver . find_element ( id : 'click' )
driver . action
. click ( clickable )
. perform
expect ( driver . current_url ) . to include 'resultPage.html'
end
describe 'alternate button clicks' do
it 'right click' do
driver . get 'https://www.selenium.dev/selenium/web/mouse_interaction.html'
clickable = driver . find_element ( id : 'clickable' )
driver . action
. context_click ( clickable )
. perform
expect ( driver . find_element ( id : 'click-status' ) . text ) . to eq 'context-clicked'
end
it 'back click' do
driver . get 'https://www.selenium.dev/selenium/web/mouse_interaction.html'
driver . find_element ( id : 'click' ) . click
expect ( driver . title ) . to eq ( 'We Arrive Here' )
driver . action
. pointer_down ( :back )
. pointer_up ( :back )
. perform
expect ( driver . title ) . to eq ( 'BasicMouseInterfaceTest' )
end
it 'forward click' do
driver . get 'https://www.selenium.dev/selenium/web/mouse_interaction.html'
driver . find_element ( id : 'click' ) . click
driver . navigate . back
expect ( driver . title ) . to eq ( 'BasicMouseInterfaceTest' )
driver . action
. pointer_down ( :forward )
. pointer_up ( :forward )
. perform
expect ( driver . title ) . to eq ( 'We Arrive Here' )
end
end
it 'double click' do
driver . get 'https://www.selenium.dev/selenium/web/mouse_interaction.html'
clickable = driver . find_element ( id : 'clickable' )
driver . action
. double_click ( clickable )
. perform
expect ( driver . find_element ( id : 'click-status' ) . text ) . to eq 'double-clicked'
end
it 'hovers' do
driver . get 'https://www.selenium.dev/selenium/web/mouse_interaction.html'
hoverable = driver . find_element ( id : 'hover' )
driver . action
. move_to ( hoverable )
. perform
expect ( driver . find_element ( id : 'move-status' ) . text ) . to eq 'hovered'
end
describe 'move by offset' do
it 'offset from element' do
driver . get 'https://www.selenium.dev/selenium/web/mouse_interaction.html'
driver . action . scroll_to ( driver . find_element ( id : 'bottom' )) . perform
mouse_tracker = driver . find_element ( id : 'mouse-tracker' )
driver . action
. move_to ( mouse_tracker , 8 , 11 )
. perform
rect = mouse_tracker . rect
center_x = rect . width / 2
center_y = rect . height / 2
x_coord , y_coord = driver . find_element ( id : 'relative-location' ) . text . split ( ',' ) . map ( & :to_i )
expect ( x_coord ) . to be_within ( 1 ) . of ( center_x + 8 )
expect ( y_coord ) . to be_within ( 1 ) . of ( center_y + 11 )
end
it 'offset from viewport' do
driver . get 'https://www.selenium.dev/selenium/web/mouse_interaction.html'
driver . action
. move_to_location ( 8 , 12 )
. perform
x_coord , y_coord = driver . find_element ( id : 'absolute-location' ) . text . split ( ',' ) . map ( & :to_i )
expect ( x_coord ) . to be_within ( 1 ) . of ( 8 )
expect ( y_coord ) . to be_within ( 1 ) . of ( 12 )
end
it 'offset from current pointer location' do
driver . get 'https://www.selenium.dev/selenium/web/mouse_interaction.html'
driver . action . move_to_location ( 8 , 11 ) . perform
driver . action
. move_by ( 13 , 15 )
. perform
x_coord , y_coord = driver . find_element ( id : 'absolute-location' ) . text . split ( ',' ) . map ( & :to_i )
expect ( x_coord ) . to be_within ( 1 ) . of ( 8 + 13 )
expect ( y_coord ) . to be_within ( 1 ) . of ( 11 + 15 )
end
end
it 'drags to another element' do
driver . get 'https://www.selenium.dev/selenium/web/mouse_interaction.html'
draggable = driver . find_element ( id : 'draggable' )
droppable = driver . find_element ( id : 'droppable' )
driver . action
. drag_and_drop ( draggable , droppable )
. perform
expect ( driver . find_element ( id : 'drop-status' ) . text ) . to include ( 'dropped' )
end
it 'drags by an offset' do
driver . get 'https://www.selenium.dev/selenium/web/mouse_interaction.html'
draggable = driver . find_element ( id : 'draggable' )
start = draggable . rect
finish = driver . find_element ( id : 'droppable' ) . rect
driver . action
. drag_and_drop_by ( draggable , finish . x - start . x , finish . y - start . y )
. perform
expect ( driver . find_element ( id : 'drop-status' ) . text ) . to include ( 'dropped' )
end
end
const mouseTracker = driver . findElement ( By . id ( "mouse-tracker" ));
const actions = driver . actions ({ async : true });
await actions . move ({ x : 8 , y : 0 , origin : mouseTracker }). perform ();
Show full example const { By , Origin , Builder } = require ( 'selenium-webdriver' );
const assert = require ( 'assert' );
describe ( 'Mouse move by offset' , function () {
let driver ;
before ( async function () {
driver = new Builder (). forBrowser ( 'chrome' ). build ();
});
after ( async () => await driver . quit ());
it ( 'From element' , async function () {
await driver . get ( 'https://www.selenium.dev/selenium/web/mouse_interaction.html' );
const mouseTracker = driver . findElement ( By . id ( "mouse-tracker" ));
const actions = driver . actions ({ async : true });
await actions . move ({ x : 8 , y : 0 , origin : mouseTracker }). perform ();
await driver . sleep ( 500 );
let result = await driver . findElement ( By . id ( 'relative-location' )). getText ();
result = result . split ( ', ' );
assert . deepStrictEqual (( Math . abs ( parseInt ( result [ 0 ]) - 100 - 8 ) < 2 ), true )
});
it ( 'From viewport origin' , async function () {
await driver . get ( 'https://www.selenium.dev/selenium/web/mouse_interaction.html' );
const actions = driver . actions ({ async : true });
await actions . move ({ x : 8 , y : 0 }). perform ();
let result = await driver . findElement ( By . id ( 'absolute-location' )). getText ();
result = result . split ( ', ' );
assert . deepStrictEqual (( Math . abs ( parseInt ( result [ 0 ]) - 8 ) < 2 ), true )
});
it ( 'From current pointer location' , async function () {
await driver . get ( 'https://selenium.dev/selenium/web/mouse_interaction.html' );
const actions = driver . actions ({ async : true });
await actions . move ({ x : 6 , y : 3 }). perform ()
await actions . move ({ x : 13 , y : 15 , origin : Origin . POINTER }). perform ()
let result = await driver . findElement ( By . id ( 'absolute-location' )). getText ();
result = result . split ( ', ' );
assert . deepStrictEqual ( Math . abs ( parseInt ( result [ 0 ]) - 6 - 13 ) < 2 , true )
assert . deepStrictEqual ( Math . abs ( parseInt ( result [ 1 ]) - 3 - 15 ) < 2 , true )
});
});
val tracker = driver . findElement ( By . id ( "mouse-tracker" ))
Actions ( driver )
. moveToElement ( tracker , 8 , 0 )
. perform ()
Show full example 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.Rectangle
import org.openqa.selenium.WebElement
import org.openqa.selenium.interactions.Actions
import org.openqa.selenium.interactions.PointerInput
import org.openqa.selenium.interactions.Sequence
import org.openqa.selenium.remote.RemoteWebDriver
import java.time.Duration
import java.util.Collections
class MouseTest : BaseTest () {
@Test
fun clickAndHold () {
driver . get ( "https://www.selenium.dev/selenium/web/mouse_interaction.html" )
val clickable = driver . findElement ( By . id ( "clickable" ))
Actions ( driver )
. clickAndHold ( clickable )
. perform ()
Assertions . assertEquals ( "focused" , driver . findElement ( By . id ( "click-status" )). getText ())
}
@Test
fun clickAndRelease () {
driver . get ( "https://www.selenium.dev/selenium/web/mouse_interaction.html" )
val clickable = driver . findElement ( By . id ( "click" ))
Actions ( driver )
. click ( clickable )
. perform ()
Assertions . assertTrue ( driver . getCurrentUrl () !! . contains ( "resultPage.html" ))
}
@Test
fun rightClick () {
driver . get ( "https://www.selenium.dev/selenium/web/mouse_interaction.html" )
val clickable = driver . findElement ( By . id ( "clickable" ))
Actions ( driver )
. contextClick ( clickable )
. perform ()
Assertions . assertEquals ( "context-clicked" , driver . findElement ( By . id ( "click-status" )). getText ())
}
@Test
fun backClick () {
driver . get ( "https://www.selenium.dev/selenium/web/mouse_interaction.html" )
driver . findElement ( By . id ( "click" )). click ()
Assertions . assertEquals ( driver . getTitle (), "We Arrive Here" )
val mouse = PointerInput ( PointerInput . Kind . MOUSE , "default mouse" )
val actions = Sequence ( mouse , 0 )
. addAction ( mouse . createPointerDown ( PointerInput . MouseButton . BACK . asArg ()))
. addAction ( mouse . createPointerUp ( PointerInput . MouseButton . BACK . asArg ()))
( driver as RemoteWebDriver ). perform ( Collections . singletonList ( actions ))
Assertions . assertEquals ( "BasicMouseInterfaceTest" , driver . getTitle ())
}
@Test
fun forwardClick () {
driver . get ( "https://www.selenium.dev/selenium/web/mouse_interaction.html" )
driver . findElement ( By . id ( "click" )). click ()
driver . navigate (). back ()
Assertions . assertEquals ( driver . getTitle (), "BasicMouseInterfaceTest" )
val mouse = PointerInput ( PointerInput . Kind . MOUSE , "default mouse" )
val actions = Sequence ( mouse , 0 )
. addAction ( mouse . createPointerDown ( PointerInput . MouseButton . FORWARD . asArg ()))
. addAction ( mouse . createPointerUp ( PointerInput . MouseButton . FORWARD . asArg ()))
( driver as RemoteWebDriver ). perform ( Collections . singletonList ( actions ))
Assertions . assertEquals ( "We Arrive Here" , driver . getTitle ())
}
@Test
fun doubleClick () {
driver . get ( "https://www.selenium.dev/selenium/web/mouse_interaction.html" )
val clickable = driver . findElement ( By . id ( "clickable" ))
Actions ( driver )
. doubleClick ( clickable )
. perform ()
Assertions . assertEquals ( "double-clicked" , driver . findElement ( By . id ( "click-status" )). getText ())
}
@Test
fun hovers () {
driver . get ( "https://www.selenium.dev/selenium/web/mouse_interaction.html" )
val hoverable = driver . findElement ( By . id ( "hover" ))
Actions ( driver )
. moveToElement ( hoverable )
. perform ()
Assertions . assertEquals ( "hovered" , driver . findElement ( By . id ( "move-status" )). getText ())
}
@Test
fun moveByOffsetFromElement () {
driver . get ( "https://www.selenium.dev/selenium/web/mouse_interaction.html" )
driver . manage (). window (). fullscreen ()
val tracker = driver . findElement ( By . id ( "mouse-tracker" ))
Actions ( driver )
. moveToElement ( tracker , 8 , 0 )
. perform ()
val result = driver . findElement ( By . id ( "relative-location" )). getText (). split ( ", " )
Assertions . assertTrue ( Math . abs ( Integer . parseInt ( result [ 0 ]) - 100 - 8 ) < 2 )
}
@Test
fun moveByOffsetFromViewport () {
driver . get ( "https://www.selenium.dev/selenium/web/mouse_interaction.html" )
val mouse = PointerInput ( PointerInput . Kind . MOUSE , "default mouse" )
val actions = Sequence ( mouse , 0 )
. addAction ( mouse . createPointerMove ( Duration . ZERO , PointerInput . Origin . viewport (), 8 , 12 ))
( driver as RemoteWebDriver ). perform ( Collections . singletonList ( actions ))
val result = driver . findElement ( By . id ( "absolute-location" )). getText (). split ( ", " )
Assertions . assertTrue ( Math . abs ( Integer . parseInt ( result [ 0 ]) - 8 ) < 2 )
Assertions . assertTrue ( Math . abs ( Integer . parseInt ( result [ 1 ]) - 12 ) < 2 )
}
@Test
fun moveByOffsetFromCurrentPointer () {
driver . get ( "https://www.selenium.dev/selenium/web/mouse_interaction.html" )
val mouse = PointerInput ( PointerInput . Kind . MOUSE , "default mouse" )
val actions = Sequence ( mouse , 0 )
. addAction ( mouse . createPointerMove ( Duration . ZERO , PointerInput . Origin . viewport (), 8 , 11 ))
( driver as RemoteWebDriver ). perform ( Collections . singletonList ( actions ))
Actions ( driver )
. moveByOffset ( 13 , 15 )
. perform ()
val result = driver . findElement ( By . id ( "absolute-location" )). getText (). split ( ", " )
Assertions . assertTrue ( Math . abs ( Integer . parseInt ( result [ 0 ]) - 8 - 13 ) < 2 )
Assertions . assertTrue ( Math . abs ( Integer . parseInt ( result [ 1 ]) - 11 - 15 ) < 2 )
}
@Test
fun dragsToElement () {
driver . get ( "https://www.selenium.dev/selenium/web/mouse_interaction.html" )
val draggable = driver . findElement ( By . id ( "draggable" ))
val droppable = driver . findElement ( By . id ( "droppable" ))
Actions ( driver )
. dragAndDrop ( draggable , droppable )
. perform ()
Assertions . assertEquals ( "dropped" , driver . findElement ( By . id ( "drop-status" )). getText ())
}
@Test
fun dragsByOffset () {
driver . get ( "https://www.selenium.dev/selenium/web/mouse_interaction.html" )
val draggable = driver . findElement ( By . id ( "draggable" ))
val start = draggable . getRect ()
val finish = driver . findElement ( By . id ( "droppable" )). getRect ()
Actions ( driver )
. dragAndDropBy ( draggable , finish . getX () - start . getX (), finish . getY () - start . getY ())
. perform ()
Assertions . assertEquals ( "dropped" , driver . findElement ( By . id ( "drop-status" )). getText ())
}
}
Deslocamento a partir da Janela de Visualização Este método move o mouse a partir do canto superior esquerdo da janela de visualização atual pelo deslocamento fornecido.
Java
Python
CSharp
Ruby
JavaScript
Kotlin PointerInput mouse = new PointerInput ( PointerInput . Kind . MOUSE , "default mouse" );
Sequence actions = new Sequence ( mouse , 0 )
. addAction ( mouse . createPointerMove ( Duration . ZERO , PointerInput . Origin . viewport (), 8 , 12 ));
(( RemoteWebDriver ) driver ). perform ( Collections . singletonList ( actions ));
Show full example 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.Rectangle ;
import org.openqa.selenium.WebElement ;
import org.openqa.selenium.interactions.Actions ;
import org.openqa.selenium.interactions.PointerInput ;
import org.openqa.selenium.interactions.Sequence ;
import org.openqa.selenium.remote.RemoteWebDriver ;
import java.time.Duration ;
import java.util.Collections ;
public class MouseTest extends BaseChromeTest {
@Test
public void clickAndHold () {
driver . get ( "https://www.selenium.dev/selenium/web/mouse_interaction.html" );
WebElement clickable = driver . findElement ( By . id ( "clickable" ));
new Actions ( driver )
. clickAndHold ( clickable )
. perform ();
Assertions . assertEquals ( "focused" , driver . findElement ( By . id ( "click-status" )). getText ());
}
@Test
public void clickAndRelease () {
driver . get ( "https://www.selenium.dev/selenium/web/mouse_interaction.html" );
WebElement clickable = driver . findElement ( By . id ( "click" ));
new Actions ( driver )
. click ( clickable )
. perform ();
Assertions . assertTrue ( driver . getCurrentUrl (). contains ( "resultPage.html" ));
}
@Test
public void rightClick () {
driver . get ( "https://www.selenium.dev/selenium/web/mouse_interaction.html" );
WebElement clickable = driver . findElement ( By . id ( "clickable" ));
new Actions ( driver )
. contextClick ( clickable )
. perform ();
Assertions . assertEquals ( "context-clicked" , driver . findElement ( By . id ( "click-status" )). getText ());
}
@Test
public void backClick () {
driver . get ( "https://www.selenium.dev/selenium/web/mouse_interaction.html" );
driver . findElement ( By . id ( "click" )). click ();
Assertions . assertEquals ( driver . getTitle (), "We Arrive Here" );
PointerInput mouse = new PointerInput ( PointerInput . Kind . MOUSE , "default mouse" );
Sequence actions = new Sequence ( mouse , 0 )
. addAction ( mouse . createPointerDown ( PointerInput . MouseButton . BACK . asArg ()))
. addAction ( mouse . createPointerUp ( PointerInput . MouseButton . BACK . asArg ()));
(( RemoteWebDriver ) driver ). perform ( Collections . singletonList ( actions ));
Assertions . assertEquals ( "BasicMouseInterfaceTest" , driver . getTitle ());
}
@Test
public void forwardClick () {
driver . get ( "https://www.selenium.dev/selenium/web/mouse_interaction.html" );
driver . findElement ( By . id ( "click" )). click ();
driver . navigate (). back ();
Assertions . assertEquals ( driver . getTitle (), "BasicMouseInterfaceTest" );
PointerInput mouse = new PointerInput ( PointerInput . Kind . MOUSE , "default mouse" );
Sequence actions = new Sequence ( mouse , 0 )
. addAction ( mouse . createPointerDown ( PointerInput . MouseButton . FORWARD . asArg ()))
. addAction ( mouse . createPointerUp ( PointerInput . MouseButton . FORWARD . asArg ()));
(( RemoteWebDriver ) driver ). perform ( Collections . singletonList ( actions ));
Assertions . assertEquals ( "We Arrive Here" , driver . getTitle ());
}
@Test
public void doubleClick () {
driver . get ( "https://www.selenium.dev/selenium/web/mouse_interaction.html" );
WebElement clickable = driver . findElement ( By . id ( "clickable" ));
new Actions ( driver )
. doubleClick ( clickable )
. perform ();
Assertions . assertEquals ( "double-clicked" , driver . findElement ( By . id ( "click-status" )). getText ());
}
@Test
public void hovers () {
driver . get ( "https://www.selenium.dev/selenium/web/mouse_interaction.html" );
WebElement hoverable = driver . findElement ( By . id ( "hover" ));
new Actions ( driver )
. moveToElement ( hoverable )
. perform ();
Assertions . assertEquals ( "hovered" , driver . findElement ( By . id ( "move-status" )). getText ());
}
@Test
public void moveByOffsetFromElement () {
driver . get ( "https://www.selenium.dev/selenium/web/mouse_interaction.html" );
driver . manage (). window (). fullscreen ();
WebElement tracker = driver . findElement ( By . id ( "mouse-tracker" ));
new Actions ( driver )
. moveToElement ( tracker , 8 , 0 )
. perform ();
String [] result = driver . findElement ( By . id ( "relative-location" )). getText (). split ( ", " );
Assertions . assertTrue ( Math . abs ( Integer . parseInt ( result [ 0 ] ) - 100 - 8 ) < 2 );
}
@Test
public void moveByOffsetFromViewport () {
driver . get ( "https://www.selenium.dev/selenium/web/mouse_interaction.html" );
PointerInput mouse = new PointerInput ( PointerInput . Kind . MOUSE , "default mouse" );
Sequence actions = new Sequence ( mouse , 0 )
. addAction ( mouse . createPointerMove ( Duration . ZERO , PointerInput . Origin . viewport (), 8 , 12 ));
(( RemoteWebDriver ) driver ). perform ( Collections . singletonList ( actions ));
String [] result = driver . findElement ( By . id ( "absolute-location" )). getText (). split ( ", " );
Assertions . assertTrue ( Math . abs ( Integer . parseInt ( result [ 0 ] ) - 8 ) < 2 );
Assertions . assertTrue ( Math . abs ( Integer . parseInt ( result [ 1 ] ) - 12 ) < 2 );
}
@Test
public void moveByOffsetFromCurrentPointer () {
driver . get ( "https://www.selenium.dev/selenium/web/mouse_interaction.html" );
PointerInput mouse = new PointerInput ( PointerInput . Kind . MOUSE , "default mouse" );
Sequence actions = new Sequence ( mouse , 0 )
. addAction ( mouse . createPointerMove ( Duration . ZERO , PointerInput . Origin . viewport (), 8 , 11 ));
(( RemoteWebDriver ) driver ). perform ( Collections . singletonList ( actions ));
new Actions ( driver )
. moveByOffset ( 13 , 15 )
. perform ();
String [] result = driver . findElement ( By . id ( "absolute-location" )). getText (). split ( ", " );
Assertions . assertTrue ( Math . abs ( Integer . parseInt ( result [ 0 ] ) - 8 - 13 ) < 2 );
Assertions . assertTrue ( Math . abs ( Integer . parseInt ( result [ 1 ] ) - 11 - 15 ) < 2 );
}
@Test
public void dragsToElement () {
driver . get ( "https://www.selenium.dev/selenium/web/mouse_interaction.html" );
WebElement draggable = driver . findElement ( By . id ( "draggable" ));
WebElement droppable = driver . findElement ( By . id ( "droppable" ));
new Actions ( driver )
. dragAndDrop ( draggable , droppable )
. perform ();
Assertions . assertEquals ( "dropped" , driver . findElement ( By . id ( "drop-status" )). getText ());
}
@Test
public void dragsByOffset () {
driver . get ( "https://www.selenium.dev/selenium/web/mouse_interaction.html" );
WebElement draggable = driver . findElement ( By . id ( "draggable" ));
Rectangle start = draggable . getRect ();
Rectangle finish = driver . findElement ( By . id ( "droppable" )). getRect ();
new Actions ( driver )
. dragAndDropBy ( draggable , finish . getX () - start . getX (), finish . getY () - start . getY ())
. perform ();
Assertions . assertEquals ( "dropped" , driver . findElement ( By . id ( "drop-status" )). getText ());
}
}
action = ActionBuilder ( driver )
action . pointer_action . move_to_location ( 8 , 0 )
action . perform ()
Show full example import pytest
from time import sleep
from selenium.webdriver import ActionChains
from selenium.webdriver.common.actions.action_builder import ActionBuilder
from selenium.webdriver.common.actions.mouse_button import MouseButton
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
def test_click_and_hold ( driver ):
driver . get ( 'https://selenium.dev/selenium/web/mouse_interaction.html' )
clickable = driver . find_element ( By . ID , "clickable" )
ActionChains ( driver ) \
. click_and_hold ( clickable ) \
. perform ()
sleep ( 0.5 )
assert driver . find_element ( By . ID , "click-status" ) . text == "focused"
def test_click_and_release ( driver ):
driver . get ( 'https://selenium.dev/selenium/web/mouse_interaction.html' )
clickable = driver . find_element ( By . ID , "click" )
ActionChains ( driver ) \
. click ( clickable ) \
. perform ()
assert "resultPage.html" in driver . current_url
def test_right_click ( driver ):
driver . get ( 'https://selenium.dev/selenium/web/mouse_interaction.html' )
clickable = driver . find_element ( By . ID , "clickable" )
ActionChains ( driver ) \
. context_click ( clickable ) \
. perform ()
sleep ( 0.5 )
assert driver . find_element ( By . ID , "click-status" ) . text == "context-clicked"
def test_back_click_ab ( driver ):
driver . get ( 'https://selenium.dev/selenium/web/mouse_interaction.html' )
driver . find_element ( By . ID , "click" ) . click ()
assert driver . title == "We Arrive Here"
action = ActionBuilder ( driver )
action . pointer_action . pointer_down ( MouseButton . BACK )
action . pointer_action . pointer_up ( MouseButton . BACK )
action . perform ()
assert driver . title == "BasicMouseInterfaceTest"
def test_forward_click_ab ( driver ):
driver . get ( 'https://selenium.dev/selenium/web/mouse_interaction.html' )
driver . find_element ( By . ID , "click" ) . click ()
driver . back ()
assert driver . title == "BasicMouseInterfaceTest"
action = ActionBuilder ( driver )
action . pointer_action . pointer_down ( MouseButton . FORWARD )
action . pointer_action . pointer_up ( MouseButton . FORWARD )
action . perform ()
assert driver . title == "We Arrive Here"
def test_double_click ( driver ):
driver . get ( 'https://selenium.dev/selenium/web/mouse_interaction.html' )
clickable = driver . find_element ( By . ID , "clickable" )
ActionChains ( driver ) \
. double_click ( clickable ) \
. perform ()
assert driver . find_element ( By . ID , "click-status" ) . text == "double-clicked"
def test_hover ( driver ):
driver . get ( 'https://selenium.dev/selenium/web/mouse_interaction.html' )
hoverable = driver . find_element ( By . ID , "hover" )
ActionChains ( driver ) \
. move_to_element ( hoverable ) \
. perform ()
assert driver . find_element ( By . ID , "move-status" ) . text == "hovered"
def test_move_by_offset_from_element ( driver ):
driver . get ( 'https://selenium.dev/selenium/web/mouse_interaction.html' )
mouse_tracker = driver . find_element ( By . ID , "mouse-tracker" )
ActionChains ( driver ) \
. move_to_element_with_offset ( mouse_tracker , 8 , 0 ) \
. perform ()
coordinates = driver . find_element ( By . ID , "relative-location" ) . text . split ( ", " )
assert abs ( int ( coordinates [ 0 ]) - 100 - 8 ) < 2
def test_move_by_offset_from_viewport_origin_ab ( driver ):
driver . get ( 'https://selenium.dev/selenium/web/mouse_interaction.html' )
WebDriverWait ( driver , 10 ) . until ( EC . presence_of_element_located (( By . ID , "absolute-location" )))
action = ActionBuilder ( driver )
action . pointer_action . move_to_location ( 8 , 0 )
action . perform ()
coordinates = driver . find_element ( By . ID , "absolute-location" ) . text . split ( ", " )
assert abs ( int ( coordinates [ 0 ]) - 8 ) < 2
def test_move_by_offset_from_current_pointer_ab ( driver ):
driver . get ( 'https://selenium.dev/selenium/web/mouse_interaction.html' )
action = ActionBuilder ( driver )
action . pointer_action . move_to_location ( 6 , 3 )
action . perform ()
ActionChains ( driver ) \
. move_by_offset ( 13 , 15 ) \
. perform ()
coordinates = driver . find_element ( By . ID , "absolute-location" ) . text . split ( ", " )
assert abs ( int ( coordinates [ 0 ]) - 6 - 13 ) < 2
assert abs ( int ( coordinates [ 1 ]) - 3 - 15 ) < 2
def test_drag_and_drop_onto_element ( driver ):
driver . get ( 'https://selenium.dev/selenium/web/mouse_interaction.html' )
draggable = driver . find_element ( By . ID , "draggable" )
droppable = driver . find_element ( By . ID , "droppable" )
ActionChains ( driver ) \
. drag_and_drop ( draggable , droppable ) \
. perform ()
assert driver . find_element ( By . ID , "drop-status" ) . text == "dropped"
def test_drag_and_drop_by_offset ( driver ):
driver . get ( 'https://selenium.dev/selenium/web/mouse_interaction.html' )
draggable = driver . find_element ( By . ID , "draggable" )
start = draggable . location
finish = driver . find_element ( By . ID , "droppable" ) . location
ActionChains ( driver ) \
. drag_and_drop_by_offset ( draggable , finish [ 'x' ] - start [ 'x' ], finish [ 'y' ] - start [ 'y' ]) \
. perform ()
assert driver . find_element ( By . ID , "drop-status" ) . text == "dropped"
ActionBuilder actionBuilder = new ActionBuilder ();
PointerInputDevice mouse = new PointerInputDevice ( PointerKind . Mouse , "default mouse" );
actionBuilder . AddAction ( mouse . CreatePointerMove ( CoordinateOrigin . Viewport ,
8 , 0 , TimeSpan . Zero ));
(( IActionExecutor ) driver ). PerformActions ( actionBuilder . ToActionSequenceList ());
Show full example using System ;
using System.Drawing ;
using Microsoft.VisualStudio.TestTools.UnitTesting ;
using OpenQA.Selenium ;
using OpenQA.Selenium.Interactions ;
namespace SeleniumDocs.ActionsAPI
{
[TestClass]
public class MouseTest : BaseChromeTest
{
[TestMethod]
public void ClickAndHold ()
{
driver . Url = "https://selenium.dev/selenium/web/mouse_interaction.html" ;
IWebElement clickable = driver . FindElement ( By . Id ( "clickable" ));
new Actions ( driver )
. ClickAndHold ( clickable )
. Perform ();
Assert . AreEqual ( "focused" , driver . FindElement ( By . Id ( "click-status" )). Text );
}
[TestMethod]
public void ClickAndRelease ()
{
driver . Url = "https://selenium.dev/selenium/web/mouse_interaction.html" ;
IWebElement clickable = driver . FindElement ( By . Id ( "click" ));
new Actions ( driver )
. Click ( clickable )
. Perform ();
Assert . IsTrue ( driver . Url . Contains ( "resultPage.html" ));
}
[TestMethod]
public void RightClick ()
{
driver . Url = "https://selenium.dev/selenium/web/mouse_interaction.html" ;
IWebElement clickable = driver . FindElement ( By . Id ( "clickable" ));
new Actions ( driver )
. ContextClick ( clickable )
. Perform ();
Assert . AreEqual ( "context-clicked" , driver . FindElement ( By . Id ( "click-status" )). Text );
}
[TestMethod]
public void BackClick ()
{
driver . Url = "https://selenium.dev/selenium/web/mouse_interaction.html" ;
driver . FindElement ( By . Id ( "click" )). Click ();
Assert . AreEqual ( "We Arrive Here" , driver . Title );
ActionBuilder actionBuilder = new ActionBuilder ();
PointerInputDevice mouse = new PointerInputDevice ( PointerKind . Mouse , "default mouse" );
actionBuilder . AddAction ( mouse . CreatePointerDown ( MouseButton . Back ));
actionBuilder . AddAction ( mouse . CreatePointerUp ( MouseButton . Back ));
(( IActionExecutor ) driver ). PerformActions ( actionBuilder . ToActionSequenceList ());
Assert . AreEqual ( "BasicMouseInterfaceTest" , driver . Title );
}
[TestMethod]
public void ForwardClick ()
{
driver . Url = "https://selenium.dev/selenium/web/mouse_interaction.html" ;
driver . FindElement ( By . Id ( "click" )). Click ();
driver . Navigate (). Back ();
Assert . AreEqual ( "BasicMouseInterfaceTest" , driver . Title );
ActionBuilder actionBuilder = new ActionBuilder ();
PointerInputDevice mouse = new PointerInputDevice ( PointerKind . Mouse , "default mouse" );
actionBuilder . AddAction ( mouse . CreatePointerDown ( MouseButton . Forward ));
actionBuilder . AddAction ( mouse . CreatePointerUp ( MouseButton . Forward ));
(( IActionExecutor ) driver ). PerformActions ( actionBuilder . ToActionSequenceList ());
Assert . AreEqual ( "We Arrive Here" , driver . Title );
}
[TestMethod]
public void DoubleClick ()
{
driver . Url = "https://selenium.dev/selenium/web/mouse_interaction.html" ;
IWebElement clickable = driver . FindElement ( By . Id ( "clickable" ));
new Actions ( driver )
. DoubleClick ( clickable )
. Perform ();
Assert . AreEqual ( "double-clicked" , driver . FindElement ( By . Id ( "click-status" )). Text );
}
[TestMethod]
public void Hovers ()
{
driver . Url = "https://selenium.dev/selenium/web/mouse_interaction.html" ;
IWebElement hoverable = driver . FindElement ( By . Id ( "hover" ));
new Actions ( driver )
. MoveToElement ( hoverable )
. Perform ();
Assert . AreEqual ( "hovered" , driver . FindElement ( By . Id ( "move-status" )). Text );
}
[TestMethod]
[Obsolete("Obsolete")]
public void MoveByOffsetFromTopLeftOfElement ()
{
driver . Url = "https://selenium.dev/selenium/web/mouse_interaction.html" ;
IWebElement tracker = driver . FindElement ( By . Id ( "mouse-tracker" ));
new Actions ( driver )
. MoveToElement ( tracker , 8 , 0 )
. Perform ();
string [] result = driver . FindElement ( By . Id ( "relative-location" )). Text . Split ( ", " );
Assert . IsTrue ( Math . Abs ( int . Parse ( result [ 0 ]) - 100 - 8 ) < 2 );
}
[TestMethod]
public void MoveByOffsetFromCenterOfElement ()
{
driver . Url = "https://selenium.dev/selenium/web/mouse_interaction.html" ;
IWebElement tracker = driver . FindElement ( By . Id ( "mouse-tracker" ));
new Actions ( driver )
. MoveToElement ( tracker , 8 , 0 )
. Perform ();
string [] result = driver . FindElement ( By . Id ( "relative-location" )). Text . Split ( ", " );
Assert . IsTrue ( Math . Abs ( int . Parse ( result [ 0 ]) - 100 - 8 ) < 2 );
}
[TestMethod]
public void MoveByOffsetFromViewport ()
{
driver . Url = "https://selenium.dev/selenium/web/mouse_interaction.html" ;
ActionBuilder actionBuilder = new ActionBuilder ();
PointerInputDevice mouse = new PointerInputDevice ( PointerKind . Mouse , "default mouse" );
actionBuilder . AddAction ( mouse . CreatePointerMove ( CoordinateOrigin . Viewport ,
8 , 0 , TimeSpan . Zero ));
(( IActionExecutor ) driver ). PerformActions ( actionBuilder . ToActionSequenceList ());
string [] result = driver . FindElement ( By . Id ( "absolute-location" )). Text . Split ( ", " );
Assert . IsTrue ( Math . Abs ( int . Parse ( result [ 0 ]) - 8 ) < 2 );
}
[TestMethod]
public void MoveByOffsetFromCurrentPointerLocation ()
{
driver . Url = "https://selenium.dev/selenium/web/mouse_interaction.html" ;
ActionBuilder actionBuilder = new ActionBuilder ();
PointerInputDevice mouse = new PointerInputDevice ( PointerKind . Mouse , "default mouse" );
actionBuilder . AddAction ( mouse . CreatePointerMove ( CoordinateOrigin . Viewport ,
8 , 12 , TimeSpan . Zero ));
(( IActionExecutor ) driver ). PerformActions ( actionBuilder . ToActionSequenceList ());
new Actions ( driver )
. MoveByOffset ( 13 , 15 )
. Perform ();
string [] result = driver . FindElement ( By . Id ( "absolute-location" )). Text . Split ( ", " );
Assert . IsTrue ( Math . Abs ( int . Parse ( result [ 0 ]) - 8 - 13 ) < 2 );
Assert . IsTrue ( Math . Abs ( int . Parse ( result [ 1 ]) - 12 - 15 ) < 2 );
}
[TestMethod]
public void DragToElement ()
{
driver . Url = "https://selenium.dev/selenium/web/mouse_interaction.html" ;
IWebElement draggable = driver . FindElement ( By . Id ( "draggable" ));
IWebElement droppable = driver . FindElement ( By . Id ( "droppable" ));
new Actions ( driver )
. DragAndDrop ( draggable , droppable )
. Perform ();
Assert . AreEqual ( "dropped" , driver . FindElement ( By . Id ( "drop-status" )). Text );
}
[TestMethod]
public void DragByOffset ()
{
driver . Url = "https://selenium.dev/selenium/web/mouse_interaction.html" ;
IWebElement draggable = driver . FindElement ( By . Id ( "draggable" ));
Point start = draggable . Location ;
Point finish = driver . FindElement ( By . Id ( "droppable" )). Location ;
new Actions ( driver )
. DragAndDropToOffset ( draggable , finish . X - start . X , finish . Y - start . Y )
. Perform ();
Assert . AreEqual ( "dropped" , driver . FindElement ( By . Id ( "drop-status" )). Text );
}
}
}
driver . action
. move_to_location ( 8 , 12 )
. perform
Show full example # frozen_string_literal: true
require 'spec_helper'
RSpec . describe 'Mouse' do
let ( :driver ) { start_session }
it 'click and hold' do
driver . get 'https://www.selenium.dev/selenium/web/mouse_interaction.html'
clickable = driver . find_element ( id : 'clickable' )
driver . action
. click_and_hold ( clickable )
. perform
expect ( driver . find_element ( id : 'click-status' ) . text ) . to eq 'focused'
end
it 'click and release' do
driver . get 'https://www.selenium.dev/selenium/web/mouse_interaction.html'
clickable = driver . find_element ( id : 'click' )
driver . action
. click ( clickable )
. perform
expect ( driver . current_url ) . to include 'resultPage.html'
end
describe 'alternate button clicks' do
it 'right click' do
driver . get 'https://www.selenium.dev/selenium/web/mouse_interaction.html'
clickable = driver . find_element ( id : 'clickable' )
driver . action
. context_click ( clickable )
. perform
expect ( driver . find_element ( id : 'click-status' ) . text ) . to eq 'context-clicked'
end
it 'back click' do
driver . get 'https://www.selenium.dev/selenium/web/mouse_interaction.html'
driver . find_element ( id : 'click' ) . click
expect ( driver . title ) . to eq ( 'We Arrive Here' )
driver . action
. pointer_down ( :back )
. pointer_up ( :back )
. perform
expect ( driver . title ) . to eq ( 'BasicMouseInterfaceTest' )
end
it 'forward click' do
driver . get 'https://www.selenium.dev/selenium/web/mouse_interaction.html'
driver . find_element ( id : 'click' ) . click
driver . navigate . back
expect ( driver . title ) . to eq ( 'BasicMouseInterfaceTest' )
driver . action
. pointer_down ( :forward )
. pointer_up ( :forward )
. perform
expect ( driver . title ) . to eq ( 'We Arrive Here' )
end
end
it 'double click' do
driver . get 'https://www.selenium.dev/selenium/web/mouse_interaction.html'
clickable = driver . find_element ( id : 'clickable' )
driver . action
. double_click ( clickable )
. perform
expect ( driver . find_element ( id : 'click-status' ) . text ) . to eq 'double-clicked'
end
it 'hovers' do
driver . get 'https://www.selenium.dev/selenium/web/mouse_interaction.html'
hoverable = driver . find_element ( id : 'hover' )
driver . action
. move_to ( hoverable )
. perform
expect ( driver . find_element ( id : 'move-status' ) . text ) . to eq 'hovered'
end
describe 'move by offset' do
it 'offset from element' do
driver . get 'https://www.selenium.dev/selenium/web/mouse_interaction.html'
driver . action . scroll_to ( driver . find_element ( id : 'bottom' )) . perform
mouse_tracker = driver . find_element ( id : 'mouse-tracker' )
driver . action
. move_to ( mouse_tracker , 8 , 11 )
. perform
rect = mouse_tracker . rect
center_x = rect . width / 2
center_y = rect . height / 2
x_coord , y_coord = driver . find_element ( id : 'relative-location' ) . text . split ( ',' ) . map ( & :to_i )
expect ( x_coord ) . to be_within ( 1 ) . of ( center_x + 8 )
expect ( y_coord ) . to be_within ( 1 ) . of ( center_y + 11 )
end
it 'offset from viewport' do
driver . get 'https://www.selenium.dev/selenium/web/mouse_interaction.html'
driver . action
. move_to_location ( 8 , 12 )
. perform
x_coord , y_coord = driver . find_element ( id : 'absolute-location' ) . text . split ( ',' ) . map ( & :to_i )
expect ( x_coord ) . to be_within ( 1 ) . of ( 8 )
expect ( y_coord ) . to be_within ( 1 ) . of ( 12 )
end
it 'offset from current pointer location' do
driver . get 'https://www.selenium.dev/selenium/web/mouse_interaction.html'
driver . action . move_to_location ( 8 , 11 ) . perform
driver . action
. move_by ( 13 , 15 )
. perform
x_coord , y_coord = driver . find_element ( id : 'absolute-location' ) . text . split ( ',' ) . map ( & :to_i )
expect ( x_coord ) . to be_within ( 1 ) . of ( 8 + 13 )
expect ( y_coord ) . to be_within ( 1 ) . of ( 11 + 15 )
end
end
it 'drags to another element' do
driver . get 'https://www.selenium.dev/selenium/web/mouse_interaction.html'
draggable = driver . find_element ( id : 'draggable' )
droppable = driver . find_element ( id : 'droppable' )
driver . action
. drag_and_drop ( draggable , droppable )
. perform
expect ( driver . find_element ( id : 'drop-status' ) . text ) . to include ( 'dropped' )
end
it 'drags by an offset' do
driver . get 'https://www.selenium.dev/selenium/web/mouse_interaction.html'
draggable = driver . find_element ( id : 'draggable' )
start = draggable . rect
finish = driver . find_element ( id : 'droppable' ) . rect
driver . action
. drag_and_drop_by ( draggable , finish . x - start . x , finish . y - start . y )
. perform
expect ( driver . find_element ( id : 'drop-status' ) . text ) . to include ( 'dropped' )
end
end
const actions = driver . actions ({ async : true });
await actions . move ({ x : 8 , y : 0 }). perform ();
Show full example const { By , Origin , Builder } = require ( 'selenium-webdriver' );
const assert = require ( 'assert' );
describe ( 'Mouse move by offset' , function () {
let driver ;
before ( async function () {
driver = new Builder (). forBrowser ( 'chrome' ). build ();
});
after ( async () => await driver . quit ());
it ( 'From element' , async function () {
await driver . get ( 'https://www.selenium.dev/selenium/web/mouse_interaction.html' );
const mouseTracker = driver . findElement ( By . id ( "mouse-tracker" ));
const actions = driver . actions ({ async : true });
await actions . move ({ x : 8 , y : 0 , origin : mouseTracker }). perform ();
await driver . sleep ( 500 );
let result = await driver . findElement ( By . id ( 'relative-location' )). getText ();
result = result . split ( ', ' );
assert . deepStrictEqual (( Math . abs ( parseInt ( result [ 0 ]) - 100 - 8 ) < 2 ), true )
});
it ( 'From viewport origin' , async function () {
await driver . get ( 'https://www.selenium.dev/selenium/web/mouse_interaction.html' );
const actions = driver . actions ({ async : true });
await actions . move ({ x : 8 , y : 0 }). perform ();
let result = await driver . findElement ( By . id ( 'absolute-location' )). getText ();
result = result . split ( ', ' );
assert . deepStrictEqual (( Math . abs ( parseInt ( result [ 0 ]) - 8 ) < 2 ), true )
});
it ( 'From current pointer location' , async function () {
await driver . get ( 'https://selenium.dev/selenium/web/mouse_interaction.html' );
const actions = driver . actions ({ async : true });
await actions . move ({ x : 6 , y : 3 }). perform ()
await actions . move ({ x : 13 , y : 15 , origin : Origin . POINTER }). perform ()
let result = await driver . findElement ( By . id ( 'absolute-location' )). getText ();
result = result . split ( ', ' );
assert . deepStrictEqual ( Math . abs ( parseInt ( result [ 0 ]) - 6 - 13 ) < 2 , true )
assert . deepStrictEqual ( Math . abs ( parseInt ( result [ 1 ]) - 3 - 15 ) < 2 , true )
});
});
val mouse = PointerInput ( PointerInput . Kind . MOUSE , "default mouse" )
val actions = Sequence ( mouse , 0 )
. addAction ( mouse . createPointerMove ( Duration . ZERO , PointerInput . Origin . viewport (), 8 , 12 ))
( driver as RemoteWebDriver ). perform ( Collections . singletonList ( actions ))
Show full example 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.Rectangle
import org.openqa.selenium.WebElement
import org.openqa.selenium.interactions.Actions
import org.openqa.selenium.interactions.PointerInput
import org.openqa.selenium.interactions.Sequence
import org.openqa.selenium.remote.RemoteWebDriver
import java.time.Duration
import java.util.Collections
class MouseTest : BaseTest () {
@Test
fun clickAndHold () {
driver . get ( "https://www.selenium.dev/selenium/web/mouse_interaction.html" )
val clickable = driver . findElement ( By . id ( "clickable" ))
Actions ( driver )
. clickAndHold ( clickable )
. perform ()
Assertions . assertEquals ( "focused" , driver . findElement ( By . id ( "click-status" )). getText ())
}
@Test
fun clickAndRelease () {
driver . get ( "https://www.selenium.dev/selenium/web/mouse_interaction.html" )
val clickable = driver . findElement ( By . id ( "click" ))
Actions ( driver )
. click ( clickable )
. perform ()
Assertions . assertTrue ( driver . getCurrentUrl () !! . contains ( "resultPage.html" ))
}
@Test
fun rightClick () {
driver . get ( "https://www.selenium.dev/selenium/web/mouse_interaction.html" )
val clickable = driver . findElement ( By . id ( "clickable" ))
Actions ( driver )
. contextClick ( clickable )
. perform ()
Assertions . assertEquals ( "context-clicked" , driver . findElement ( By . id ( "click-status" )). getText ())
}
@Test
fun backClick () {
driver . get ( "https://www.selenium.dev/selenium/web/mouse_interaction.html" )
driver . findElement ( By . id ( "click" )). click ()
Assertions . assertEquals ( driver . getTitle (), "We Arrive Here" )
val mouse = PointerInput ( PointerInput . Kind . MOUSE , "default mouse" )
val actions = Sequence ( mouse , 0 )
. addAction ( mouse . createPointerDown ( PointerInput . MouseButton . BACK . asArg ()))
. addAction ( mouse . createPointerUp ( PointerInput . MouseButton . BACK . asArg ()))
( driver as RemoteWebDriver ). perform ( Collections . singletonList ( actions ))
Assertions . assertEquals ( "BasicMouseInterfaceTest" , driver . getTitle ())
}
@Test
fun forwardClick () {
driver . get ( "https://www.selenium.dev/selenium/web/mouse_interaction.html" )
driver . findElement ( By . id ( "click" )). click ()
driver . navigate (). back ()
Assertions . assertEquals ( driver . getTitle (), "BasicMouseInterfaceTest" )
val mouse = PointerInput ( PointerInput . Kind . MOUSE , "default mouse" )
val actions = Sequence ( mouse , 0 )
. addAction ( mouse . createPointerDown ( PointerInput . MouseButton . FORWARD . asArg ()))
. addAction ( mouse . createPointerUp ( PointerInput . MouseButton . FORWARD . asArg ()))
( driver as RemoteWebDriver ). perform ( Collections . singletonList ( actions ))
Assertions . assertEquals ( "We Arrive Here" , driver . getTitle ())
}
@Test
fun doubleClick () {
driver . get ( "https://www.selenium.dev/selenium/web/mouse_interaction.html" )
val clickable = driver . findElement ( By . id ( "clickable" ))
Actions ( driver )
. doubleClick ( clickable )
. perform ()
Assertions . assertEquals ( "double-clicked" , driver . findElement ( By . id ( "click-status" )). getText ())
}
@Test
fun hovers () {
driver . get ( "https://www.selenium.dev/selenium/web/mouse_interaction.html" )
val hoverable = driver . findElement ( By . id ( "hover" ))
Actions ( driver )
. moveToElement ( hoverable )
. perform ()
Assertions . assertEquals ( "hovered" , driver . findElement ( By . id ( "move-status" )). getText ())
}
@Test
fun moveByOffsetFromElement () {
driver . get ( "https://www.selenium.dev/selenium/web/mouse_interaction.html" )
driver . manage (). window (). fullscreen ()
val tracker = driver . findElement ( By . id ( "mouse-tracker" ))
Actions ( driver )
. moveToElement ( tracker , 8 , 0 )
. perform ()
val result = driver . findElement ( By . id ( "relative-location" )). getText (). split ( ", " )
Assertions . assertTrue ( Math . abs ( Integer . parseInt ( result [ 0 ]) - 100 - 8 ) < 2 )
}
@Test
fun moveByOffsetFromViewport () {
driver . get ( "https://www.selenium.dev/selenium/web/mouse_interaction.html" )
val mouse = PointerInput ( PointerInput . Kind . MOUSE , "default mouse" )
val actions = Sequence ( mouse , 0 )
. addAction ( mouse . createPointerMove ( Duration . ZERO , PointerInput . Origin . viewport (), 8 , 12 ))
( driver as RemoteWebDriver ). perform ( Collections . singletonList ( actions ))
val result = driver . findElement ( By . id ( "absolute-location" )). getText (). split ( ", " )
Assertions . assertTrue ( Math . abs ( Integer . parseInt ( result [ 0 ]) - 8 ) < 2 )
Assertions . assertTrue ( Math . abs ( Integer . parseInt ( result [ 1 ]) - 12 ) < 2 )
}
@Test
fun moveByOffsetFromCurrentPointer () {
driver . get ( "https://www.selenium.dev/selenium/web/mouse_interaction.html" )
val mouse = PointerInput ( PointerInput . Kind . MOUSE , "default mouse" )
val actions = Sequence ( mouse , 0 )
. addAction ( mouse . createPointerMove ( Duration . ZERO , PointerInput . Origin . viewport (), 8 , 11 ))
( driver as RemoteWebDriver ). perform ( Collections . singletonList ( actions ))
Actions ( driver )
. moveByOffset ( 13 , 15 )
. perform ()
val result = driver . findElement ( By . id ( "absolute-location" )). getText (). split ( ", " )
Assertions . assertTrue ( Math . abs ( Integer . parseInt ( result [ 0 ]) - 8 - 13 ) < 2 )
Assertions . assertTrue ( Math . abs ( Integer . parseInt ( result [ 1 ]) - 11 - 15 ) < 2 )
}
@Test
fun dragsToElement () {
driver . get ( "https://www.selenium.dev/selenium/web/mouse_interaction.html" )
val draggable = driver . findElement ( By . id ( "draggable" ))
val droppable = driver . findElement ( By . id ( "droppable" ))
Actions ( driver )
. dragAndDrop ( draggable , droppable )
. perform ()
Assertions . assertEquals ( "dropped" , driver . findElement ( By . id ( "drop-status" )). getText ())
}
@Test
fun dragsByOffset () {
driver . get ( "https://www.selenium.dev/selenium/web/mouse_interaction.html" )
val draggable = driver . findElement ( By . id ( "draggable" ))
val start = draggable . getRect ()
val finish = driver . findElement ( By . id ( "droppable" )). getRect ()
Actions ( driver )
. dragAndDropBy ( draggable , finish . getX () - start . getX (), finish . getY () - start . getY ())
. perform ()
Assertions . assertEquals ( "dropped" , driver . findElement ( By . id ( "drop-status" )). getText ())
}
}
Deslocamento a partir da Localização Atual do Ponteiro Este método move o mouse a partir de sua posição atual pelo deslocamento fornecido pelo usuário. Se o mouse não tiver sido movido anteriormente, a posição será no canto superior esquerdo da janela de visualização. É importante notar que a posição do ponteiro não muda quando a página é rolada.
Observe que o primeiro argumento, X, especifica o movimento para a direita quando positivo, enquanto o segundo argumento, Y, especifica o movimento para baixo quando positivo. Portanto, moveByOffset(30, -10)
move o mouse 30 unidades para a direita e 10 unidades para cima a partir da posição atual do mouse.
Java
Python
CSharp
Ruby
JavaScript
Kotlin new Actions ( driver )
. moveByOffset ( 13 , 15 )
. perform ();
Show full example 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.Rectangle ;
import org.openqa.selenium.WebElement ;
import org.openqa.selenium.interactions.Actions ;
import org.openqa.selenium.interactions.PointerInput ;
import org.openqa.selenium.interactions.Sequence ;
import org.openqa.selenium.remote.RemoteWebDriver ;
import java.time.Duration ;
import java.util.Collections ;
public class MouseTest extends BaseChromeTest {
@Test
public void clickAndHold () {
driver . get ( "https://www.selenium.dev/selenium/web/mouse_interaction.html" );
WebElement clickable = driver . findElement ( By . id ( "clickable" ));
new Actions ( driver )
. clickAndHold ( clickable )
. perform ();
Assertions . assertEquals ( "focused" , driver . findElement ( By . id ( "click-status" )). getText ());
}
@Test
public void clickAndRelease () {
driver . get ( "https://www.selenium.dev/selenium/web/mouse_interaction.html" );
WebElement clickable = driver . findElement ( By . id ( "click" ));
new Actions ( driver )
. click ( clickable )
. perform ();
Assertions . assertTrue ( driver . getCurrentUrl (). contains ( "resultPage.html" ));
}
@Test
public void rightClick () {
driver . get ( "https://www.selenium.dev/selenium/web/mouse_interaction.html" );
WebElement clickable = driver . findElement ( By . id ( "clickable" ));
new Actions ( driver )
. contextClick ( clickable )
. perform ();
Assertions . assertEquals ( "context-clicked" , driver . findElement ( By . id ( "click-status" )). getText ());
}
@Test
public void backClick () {
driver . get ( "https://www.selenium.dev/selenium/web/mouse_interaction.html" );
driver . findElement ( By . id ( "click" )). click ();
Assertions . assertEquals ( driver . getTitle (), "We Arrive Here" );
PointerInput mouse = new PointerInput ( PointerInput . Kind . MOUSE , "default mouse" );
Sequence actions = new Sequence ( mouse , 0 )
. addAction ( mouse . createPointerDown ( PointerInput . MouseButton . BACK . asArg ()))
. addAction ( mouse . createPointerUp ( PointerInput . MouseButton . BACK . asArg ()));
(( RemoteWebDriver ) driver ). perform ( Collections . singletonList ( actions ));
Assertions . assertEquals ( "BasicMouseInterfaceTest" , driver . getTitle ());
}
@Test
public void forwardClick () {
driver . get ( "https://www.selenium.dev/selenium/web/mouse_interaction.html" );
driver . findElement ( By . id ( "click" )). click ();
driver . navigate (). back ();
Assertions . assertEquals ( driver . getTitle (), "BasicMouseInterfaceTest" );
PointerInput mouse = new PointerInput ( PointerInput . Kind . MOUSE , "default mouse" );
Sequence actions = new Sequence ( mouse , 0 )
. addAction ( mouse . createPointerDown ( PointerInput . MouseButton . FORWARD . asArg ()))
. addAction ( mouse . createPointerUp ( PointerInput . MouseButton . FORWARD . asArg ()));
(( RemoteWebDriver ) driver ). perform ( Collections . singletonList ( actions ));
Assertions . assertEquals ( "We Arrive Here" , driver . getTitle ());
}
@Test
public void doubleClick () {
driver . get ( "https://www.selenium.dev/selenium/web/mouse_interaction.html" );
WebElement clickable = driver . findElement ( By . id ( "clickable" ));
new Actions ( driver )
. doubleClick ( clickable )
. perform ();
Assertions . assertEquals ( "double-clicked" , driver . findElement ( By . id ( "click-status" )). getText ());
}
@Test
public void hovers () {
driver . get ( "https://www.selenium.dev/selenium/web/mouse_interaction.html" );
WebElement hoverable = driver . findElement ( By . id ( "hover" ));
new Actions ( driver )
. moveToElement ( hoverable )
. perform ();
Assertions . assertEquals ( "hovered" , driver . findElement ( By . id ( "move-status" )). getText ());
}
@Test
public void moveByOffsetFromElement () {
driver . get ( "https://www.selenium.dev/selenium/web/mouse_interaction.html" );
driver . manage (). window (). fullscreen ();
WebElement tracker = driver . findElement ( By . id ( "mouse-tracker" ));
new Actions ( driver )
. moveToElement ( tracker , 8 , 0 )
. perform ();
String [] result = driver . findElement ( By . id ( "relative-location" )). getText (). split ( ", " );
Assertions . assertTrue ( Math . abs ( Integer . parseInt ( result [ 0 ] ) - 100 - 8 ) < 2 );
}
@Test
public void moveByOffsetFromViewport () {
driver . get ( "https://www.selenium.dev/selenium/web/mouse_interaction.html" );
PointerInput mouse = new PointerInput ( PointerInput . Kind . MOUSE , "default mouse" );
Sequence actions = new Sequence ( mouse , 0 )
. addAction ( mouse . createPointerMove ( Duration . ZERO , PointerInput . Origin . viewport (), 8 , 12 ));
(( RemoteWebDriver ) driver ). perform ( Collections . singletonList ( actions ));
String [] result = driver . findElement ( By . id ( "absolute-location" )). getText (). split ( ", " );
Assertions . assertTrue ( Math . abs ( Integer . parseInt ( result [ 0 ] ) - 8 ) < 2 );
Assertions . assertTrue ( Math . abs ( Integer . parseInt ( result [ 1 ] ) - 12 ) < 2 );
}
@Test
public void moveByOffsetFromCurrentPointer () {
driver . get ( "https://www.selenium.dev/selenium/web/mouse_interaction.html" );
PointerInput mouse = new PointerInput ( PointerInput . Kind . MOUSE , "default mouse" );
Sequence actions = new Sequence ( mouse , 0 )
. addAction ( mouse . createPointerMove ( Duration . ZERO , PointerInput . Origin . viewport (), 8 , 11 ));
(( RemoteWebDriver ) driver ). perform ( Collections . singletonList ( actions ));
new Actions ( driver )
. moveByOffset ( 13 , 15 )
. perform ();
String [] result = driver . findElement ( By . id ( "absolute-location" )). getText (). split ( ", " );
Assertions . assertTrue ( Math . abs ( Integer . parseInt ( result [ 0 ] ) - 8 - 13 ) < 2 );
Assertions . assertTrue ( Math . abs ( Integer . parseInt ( result [ 1 ] ) - 11 - 15 ) < 2 );
}
@Test
public void dragsToElement () {
driver . get ( "https://www.selenium.dev/selenium/web/mouse_interaction.html" );
WebElement draggable = driver . findElement ( By . id ( "draggable" ));
WebElement droppable = driver . findElement ( By . id ( "droppable" ));
new Actions ( driver )
. dragAndDrop ( draggable , droppable )
. perform ();
Assertions . assertEquals ( "dropped" , driver . findElement ( By . id ( "drop-status" )). getText ());
}
@Test
public void dragsByOffset () {
driver . get ( "https://www.selenium.dev/selenium/web/mouse_interaction.html" );
WebElement draggable = driver . findElement ( By . id ( "draggable" ));
Rectangle start = draggable . getRect ();
Rectangle finish = driver . findElement ( By . id ( "droppable" )). getRect ();
new Actions ( driver )
. dragAndDropBy ( draggable , finish . getX () - start . getX (), finish . getY () - start . getY ())
. perform ();
Assertions . assertEquals ( "dropped" , driver . findElement ( By . id ( "drop-status" )). getText ());
}
}
ActionChains ( driver ) \
. move_by_offset ( 13 , 15 ) \
. perform ()
Show full example import pytest
from time import sleep
from selenium.webdriver import ActionChains
from selenium.webdriver.common.actions.action_builder import ActionBuilder
from selenium.webdriver.common.actions.mouse_button import MouseButton
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
def test_click_and_hold ( driver ):
driver . get ( 'https://selenium.dev/selenium/web/mouse_interaction.html' )
clickable = driver . find_element ( By . ID , "clickable" )
ActionChains ( driver ) \
. click_and_hold ( clickable ) \
. perform ()
sleep ( 0.5 )
assert driver . find_element ( By . ID , "click-status" ) . text == "focused"
def test_click_and_release ( driver ):
driver . get ( 'https://selenium.dev/selenium/web/mouse_interaction.html' )
clickable = driver . find_element ( By . ID , "click" )
ActionChains ( driver ) \
. click ( clickable ) \
. perform ()
assert "resultPage.html" in driver . current_url
def test_right_click ( driver ):
driver . get ( 'https://selenium.dev/selenium/web/mouse_interaction.html' )
clickable = driver . find_element ( By . ID , "clickable" )
ActionChains ( driver ) \
. context_click ( clickable ) \
. perform ()
sleep ( 0.5 )
assert driver . find_element ( By . ID , "click-status" ) . text == "context-clicked"
def test_back_click_ab ( driver ):
driver . get ( 'https://selenium.dev/selenium/web/mouse_interaction.html' )
driver . find_element ( By . ID , "click" ) . click ()
assert driver . title == "We Arrive Here"
action = ActionBuilder ( driver )
action . pointer_action . pointer_down ( MouseButton . BACK )
action . pointer_action . pointer_up ( MouseButton . BACK )
action . perform ()
assert driver . title == "BasicMouseInterfaceTest"
def test_forward_click_ab ( driver ):
driver . get ( 'https://selenium.dev/selenium/web/mouse_interaction.html' )
driver . find_element ( By . ID , "click" ) . click ()
driver . back ()
assert driver . title == "BasicMouseInterfaceTest"
action = ActionBuilder ( driver )
action . pointer_action . pointer_down ( MouseButton . FORWARD )
action . pointer_action . pointer_up ( MouseButton . FORWARD )
action . perform ()
assert driver . title == "We Arrive Here"
def test_double_click ( driver ):
driver . get ( 'https://selenium.dev/selenium/web/mouse_interaction.html' )
clickable = driver . find_element ( By . ID , "clickable" )
ActionChains ( driver ) \
. double_click ( clickable ) \
. perform ()
assert driver . find_element ( By . ID , "click-status" ) . text == "double-clicked"
def test_hover ( driver ):
driver . get ( 'https://selenium.dev/selenium/web/mouse_interaction.html' )
hoverable = driver . find_element ( By . ID , "hover" )
ActionChains ( driver ) \
. move_to_element ( hoverable ) \
. perform ()
assert driver . find_element ( By . ID , "move-status" ) . text == "hovered"
def test_move_by_offset_from_element ( driver ):
driver . get ( 'https://selenium.dev/selenium/web/mouse_interaction.html' )
mouse_tracker = driver . find_element ( By . ID , "mouse-tracker" )
ActionChains ( driver ) \
. move_to_element_with_offset ( mouse_tracker , 8 , 0 ) \
. perform ()
coordinates = driver . find_element ( By . ID , "relative-location" ) . text . split ( ", " )
assert abs ( int ( coordinates [ 0 ]) - 100 - 8 ) < 2
def test_move_by_offset_from_viewport_origin_ab ( driver ):
driver . get ( 'https://selenium.dev/selenium/web/mouse_interaction.html' )
WebDriverWait ( driver , 10 ) . until ( EC . presence_of_element_located (( By . ID , "absolute-location" )))
action = ActionBuilder ( driver )
action . pointer_action . move_to_location ( 8 , 0 )
action . perform ()
coordinates = driver . find_element ( By . ID , "absolute-location" ) . text . split ( ", " )
assert abs ( int ( coordinates [ 0 ]) - 8 ) < 2
def test_move_by_offset_from_current_pointer_ab ( driver ):
driver . get ( 'https://selenium.dev/selenium/web/mouse_interaction.html' )
action = ActionBuilder ( driver )
action . pointer_action . move_to_location ( 6 , 3 )
action . perform ()
ActionChains ( driver ) \
. move_by_offset ( 13 , 15 ) \
. perform ()
coordinates = driver . find_element ( By . ID , "absolute-location" ) . text . split ( ", " )
assert abs ( int ( coordinates [ 0 ]) - 6 - 13 ) < 2
assert abs ( int ( coordinates [ 1 ]) - 3 - 15 ) < 2
def test_drag_and_drop_onto_element ( driver ):
driver . get ( 'https://selenium.dev/selenium/web/mouse_interaction.html' )
draggable = driver . find_element ( By . ID , "draggable" )
droppable = driver . find_element ( By . ID , "droppable" )
ActionChains ( driver ) \
. drag_and_drop ( draggable , droppable ) \
. perform ()
assert driver . find_element ( By . ID , "drop-status" ) . text == "dropped"
def test_drag_and_drop_by_offset ( driver ):
driver . get ( 'https://selenium.dev/selenium/web/mouse_interaction.html' )
draggable = driver . find_element ( By . ID , "draggable" )
start = draggable . location
finish = driver . find_element ( By . ID , "droppable" ) . location
ActionChains ( driver ) \
. drag_and_drop_by_offset ( draggable , finish [ 'x' ] - start [ 'x' ], finish [ 'y' ] - start [ 'y' ]) \
. perform ()
assert driver . find_element ( By . ID , "drop-status" ) . text == "dropped"
new Actions ( driver )
. MoveByOffset ( 13 , 15 )
. Perform ();
Show full example using System ;
using System.Drawing ;
using Microsoft.VisualStudio.TestTools.UnitTesting ;
using OpenQA.Selenium ;
using OpenQA.Selenium.Interactions ;
namespace SeleniumDocs.ActionsAPI
{
[TestClass]
public class MouseTest : BaseChromeTest
{
[TestMethod]
public void ClickAndHold ()
{
driver . Url = "https://selenium.dev/selenium/web/mouse_interaction.html" ;
IWebElement clickable = driver . FindElement ( By . Id ( "clickable" ));
new Actions ( driver )
. ClickAndHold ( clickable )
. Perform ();
Assert . AreEqual ( "focused" , driver . FindElement ( By . Id ( "click-status" )). Text );
}
[TestMethod]
public void ClickAndRelease ()
{
driver . Url = "https://selenium.dev/selenium/web/mouse_interaction.html" ;
IWebElement clickable = driver . FindElement ( By . Id ( "click" ));
new Actions ( driver )
. Click ( clickable )
. Perform ();
Assert . IsTrue ( driver . Url . Contains ( "resultPage.html" ));
}
[TestMethod]
public void RightClick ()
{
driver . Url = "https://selenium.dev/selenium/web/mouse_interaction.html" ;
IWebElement clickable = driver . FindElement ( By . Id ( "clickable" ));
new Actions ( driver )
. ContextClick ( clickable )
. Perform ();
Assert . AreEqual ( "context-clicked" , driver . FindElement ( By . Id ( "click-status" )). Text );
}
[TestMethod]
public void BackClick ()
{
driver . Url = "https://selenium.dev/selenium/web/mouse_interaction.html" ;
driver . FindElement ( By . Id ( "click" )). Click ();
Assert . AreEqual ( "We Arrive Here" , driver . Title );
ActionBuilder actionBuilder = new ActionBuilder ();
PointerInputDevice mouse = new PointerInputDevice ( PointerKind . Mouse , "default mouse" );
actionBuilder . AddAction ( mouse . CreatePointerDown ( MouseButton . Back ));
actionBuilder . AddAction ( mouse . CreatePointerUp ( MouseButton . Back ));
(( IActionExecutor ) driver ). PerformActions ( actionBuilder . ToActionSequenceList ());
Assert . AreEqual ( "BasicMouseInterfaceTest" , driver . Title );
}
[TestMethod]
public void ForwardClick ()
{
driver . Url = "https://selenium.dev/selenium/web/mouse_interaction.html" ;
driver . FindElement ( By . Id ( "click" )). Click ();
driver . Navigate (). Back ();
Assert . AreEqual ( "BasicMouseInterfaceTest" , driver . Title );
ActionBuilder actionBuilder = new ActionBuilder ();
PointerInputDevice mouse = new PointerInputDevice ( PointerKind . Mouse , "default mouse" );
actionBuilder . AddAction ( mouse . CreatePointerDown ( MouseButton . Forward ));
actionBuilder . AddAction ( mouse . CreatePointerUp ( MouseButton . Forward ));
(( IActionExecutor ) driver ). PerformActions ( actionBuilder . ToActionSequenceList ());
Assert . AreEqual ( "We Arrive Here" , driver . Title );
}
[TestMethod]
public void DoubleClick ()
{
driver . Url = "https://selenium.dev/selenium/web/mouse_interaction.html" ;
IWebElement clickable = driver . FindElement ( By . Id ( "clickable" ));
new Actions ( driver )
. DoubleClick ( clickable )
. Perform ();
Assert . AreEqual ( "double-clicked" , driver . FindElement ( By . Id ( "click-status" )). Text );
}
[TestMethod]
public void Hovers ()
{
driver . Url = "https://selenium.dev/selenium/web/mouse_interaction.html" ;
IWebElement hoverable = driver . FindElement ( By . Id ( "hover" ));
new Actions ( driver )
. MoveToElement ( hoverable )
. Perform ();
Assert . AreEqual ( "hovered" , driver . FindElement ( By . Id ( "move-status" )). Text );
}
[TestMethod]
[Obsolete("Obsolete")]
public void MoveByOffsetFromTopLeftOfElement ()
{
driver . Url = "https://selenium.dev/selenium/web/mouse_interaction.html" ;
IWebElement tracker = driver . FindElement ( By . Id ( "mouse-tracker" ));
new Actions ( driver )
. MoveToElement ( tracker , 8 , 0 )
. Perform ();
string [] result = driver . FindElement ( By . Id ( "relative-location" )). Text . Split ( ", " );
Assert . IsTrue ( Math . Abs ( int . Parse ( result [ 0 ]) - 100 - 8 ) < 2 );
}
[TestMethod]
public void MoveByOffsetFromCenterOfElement ()
{
driver . Url = "https://selenium.dev/selenium/web/mouse_interaction.html" ;
IWebElement tracker = driver . FindElement ( By . Id ( "mouse-tracker" ));
new Actions ( driver )
. MoveToElement ( tracker , 8 , 0 )
. Perform ();
string [] result = driver . FindElement ( By . Id ( "relative-location" )). Text . Split ( ", " );
Assert . IsTrue ( Math . Abs ( int . Parse ( result [ 0 ]) - 100 - 8 ) < 2 );
}
[TestMethod]
public void MoveByOffsetFromViewport ()
{
driver . Url = "https://selenium.dev/selenium/web/mouse_interaction.html" ;
ActionBuilder actionBuilder = new ActionBuilder ();
PointerInputDevice mouse = new PointerInputDevice ( PointerKind . Mouse , "default mouse" );
actionBuilder . AddAction ( mouse . CreatePointerMove ( CoordinateOrigin . Viewport ,
8 , 0 , TimeSpan . Zero ));
(( IActionExecutor ) driver ). PerformActions ( actionBuilder . ToActionSequenceList ());
string [] result = driver . FindElement ( By . Id ( "absolute-location" )). Text . Split ( ", " );
Assert . IsTrue ( Math . Abs ( int . Parse ( result [ 0 ]) - 8 ) < 2 );
}
[TestMethod]
public void MoveByOffsetFromCurrentPointerLocation ()
{
driver . Url = "https://selenium.dev/selenium/web/mouse_interaction.html" ;
ActionBuilder actionBuilder = new ActionBuilder ();
PointerInputDevice mouse = new PointerInputDevice ( PointerKind . Mouse , "default mouse" );
actionBuilder . AddAction ( mouse . CreatePointerMove ( CoordinateOrigin . Viewport ,
8 , 12 , TimeSpan . Zero ));
(( IActionExecutor ) driver ). PerformActions ( actionBuilder . ToActionSequenceList ());
new Actions ( driver )
. MoveByOffset ( 13 , 15 )
. Perform ();
string [] result = driver . FindElement ( By . Id ( "absolute-location" )). Text . Split ( ", " );
Assert . IsTrue ( Math . Abs ( int . Parse ( result [ 0 ]) - 8 - 13 ) < 2 );
Assert . IsTrue ( Math . Abs ( int . Parse ( result [ 1 ]) - 12 - 15 ) < 2 );
}
[TestMethod]
public void DragToElement ()
{
driver . Url = "https://selenium.dev/selenium/web/mouse_interaction.html" ;
IWebElement draggable = driver . FindElement ( By . Id ( "draggable" ));
IWebElement droppable = driver . FindElement ( By . Id ( "droppable" ));
new Actions ( driver )
. DragAndDrop ( draggable , droppable )
. Perform ();
Assert . AreEqual ( "dropped" , driver . FindElement ( By . Id ( "drop-status" )). Text );
}
[TestMethod]
public void DragByOffset ()
{
driver . Url = "https://selenium.dev/selenium/web/mouse_interaction.html" ;
IWebElement draggable = driver . FindElement ( By . Id ( "draggable" ));
Point start = draggable . Location ;
Point finish = driver . FindElement ( By . Id ( "droppable" )). Location ;
new Actions ( driver )
. DragAndDropToOffset ( draggable , finish . X - start . X , finish . Y - start . Y )
. Perform ();
Assert . AreEqual ( "dropped" , driver . FindElement ( By . Id ( "drop-status" )). Text );
}
}
}
driver . action
. move_by ( 13 , 15 )
. perform
Show full example # frozen_string_literal: true
require 'spec_helper'
RSpec . describe 'Mouse' do
let ( :driver ) { start_session }
it 'click and hold' do
driver . get 'https://www.selenium.dev/selenium/web/mouse_interaction.html'
clickable = driver . find_element ( id : 'clickable' )
driver . action
. click_and_hold ( clickable )
. perform
expect ( driver . find_element ( id : 'click-status' ) . text ) . to eq 'focused'
end
it 'click and release' do
driver . get 'https://www.selenium.dev/selenium/web/mouse_interaction.html'
clickable = driver . find_element ( id : 'click' )
driver . action
. click ( clickable )
. perform
expect ( driver . current_url ) . to include 'resultPage.html'
end
describe 'alternate button clicks' do
it 'right click' do
driver . get 'https://www.selenium.dev/selenium/web/mouse_interaction.html'
clickable = driver . find_element ( id : 'clickable' )
driver . action
. context_click ( clickable )
. perform
expect ( driver . find_element ( id : 'click-status' ) . text ) . to eq 'context-clicked'
end
it 'back click' do
driver . get 'https://www.selenium.dev/selenium/web/mouse_interaction.html'
driver . find_element ( id : 'click' ) . click
expect ( driver . title ) . to eq ( 'We Arrive Here' )
driver . action
. pointer_down ( :back )
. pointer_up ( :back )
. perform
expect ( driver . title ) . to eq ( 'BasicMouseInterfaceTest' )
end
it 'forward click' do
driver . get 'https://www.selenium.dev/selenium/web/mouse_interaction.html'
driver . find_element ( id : 'click' ) . click
driver . navigate . back
expect ( driver . title ) . to eq ( 'BasicMouseInterfaceTest' )
driver . action
. pointer_down ( :forward )
. pointer_up ( :forward )
. perform
expect ( driver . title ) . to eq ( 'We Arrive Here' )
end
end
it 'double click' do
driver . get 'https://www.selenium.dev/selenium/web/mouse_interaction.html'
clickable = driver . find_element ( id : 'clickable' )
driver . action
. double_click ( clickable )
. perform
expect ( driver . find_element ( id : 'click-status' ) . text ) . to eq 'double-clicked'
end
it 'hovers' do
driver . get 'https://www.selenium.dev/selenium/web/mouse_interaction.html'
hoverable = driver . find_element ( id : 'hover' )
driver . action
. move_to ( hoverable )
. perform
expect ( driver . find_element ( id : 'move-status' ) . text ) . to eq 'hovered'
end
describe 'move by offset' do
it 'offset from element' do
driver . get 'https://www.selenium.dev/selenium/web/mouse_interaction.html'
driver . action . scroll_to ( driver . find_element ( id : 'bottom' )) . perform
mouse_tracker = driver . find_element ( id : 'mouse-tracker' )
driver . action
. move_to ( mouse_tracker , 8 , 11 )
. perform
rect = mouse_tracker . rect
center_x = rect . width / 2
center_y = rect . height / 2
x_coord , y_coord = driver . find_element ( id : 'relative-location' ) . text . split ( ',' ) . map ( & :to_i )
expect ( x_coord ) . to be_within ( 1 ) . of ( center_x + 8 )
expect ( y_coord ) . to be_within ( 1 ) . of ( center_y + 11 )
end
it 'offset from viewport' do
driver . get 'https://www.selenium.dev/selenium/web/mouse_interaction.html'
driver . action
. move_to_location ( 8 , 12 )
. perform
x_coord , y_coord = driver . find_element ( id : 'absolute-location' ) . text . split ( ',' ) . map ( & :to_i )
expect ( x_coord ) . to be_within ( 1 ) . of ( 8 )
expect ( y_coord ) . to be_within ( 1 ) . of ( 12 )
end
it 'offset from current pointer location' do
driver . get 'https://www.selenium.dev/selenium/web/mouse_interaction.html'
driver . action . move_to_location ( 8 , 11 ) . perform
driver . action
. move_by ( 13 , 15 )
. perform
x_coord , y_coord = driver . find_element ( id : 'absolute-location' ) . text . split ( ',' ) . map ( & :to_i )
expect ( x_coord ) . to be_within ( 1 ) . of ( 8 + 13 )
expect ( y_coord ) . to be_within ( 1 ) . of ( 11 + 15 )
end
end
it 'drags to another element' do
driver . get 'https://www.selenium.dev/selenium/web/mouse_interaction.html'
draggable = driver . find_element ( id : 'draggable' )
droppable = driver . find_element ( id : 'droppable' )
driver . action
. drag_and_drop ( draggable , droppable )
. perform
expect ( driver . find_element ( id : 'drop-status' ) . text ) . to include ( 'dropped' )
end
it 'drags by an offset' do
driver . get 'https://www.selenium.dev/selenium/web/mouse_interaction.html'
draggable = driver . find_element ( id : 'draggable' )
start = draggable . rect
finish = driver . find_element ( id : 'droppable' ) . rect
driver . action
. drag_and_drop_by ( draggable , finish . x - start . x , finish . y - start . y )
. perform
expect ( driver . find_element ( id : 'drop-status' ) . text ) . to include ( 'dropped' )
end
end
await actions . move ({ x : 13 , y : 15 , origin : Origin . POINTER }). perform ()
Show full example const { By , Origin , Builder } = require ( 'selenium-webdriver' );
const assert = require ( 'assert' );
describe ( 'Mouse move by offset' , function () {
let driver ;
before ( async function () {
driver = new Builder (). forBrowser ( 'chrome' ). build ();
});
after ( async () => await driver . quit ());
it ( 'From element' , async function () {
await driver . get ( 'https://www.selenium.dev/selenium/web/mouse_interaction.html' );
const mouseTracker = driver . findElement ( By . id ( "mouse-tracker" ));
const actions = driver . actions ({ async : true });
await actions . move ({ x : 8 , y : 0 , origin : mouseTracker }). perform ();
await driver . sleep ( 500 );
let result = await driver . findElement ( By . id ( 'relative-location' )). getText ();
result = result . split ( ', ' );
assert . deepStrictEqual (( Math . abs ( parseInt ( result [ 0 ]) - 100 - 8 ) < 2 ), true )
});
it ( 'From viewport origin' , async function () {
await driver . get ( 'https://www.selenium.dev/selenium/web/mouse_interaction.html' );
const actions = driver . actions ({ async : true });
await actions . move ({ x : 8 , y : 0 }). perform ();
let result = await driver . findElement ( By . id ( 'absolute-location' )). getText ();
result = result . split ( ', ' );
assert . deepStrictEqual (( Math . abs ( parseInt ( result [ 0 ]) - 8 ) < 2 ), true )
});
it ( 'From current pointer location' , async function () {
await driver . get ( 'https://selenium.dev/selenium/web/mouse_interaction.html' );
const actions = driver . actions ({ async : true });
await actions . move ({ x : 6 , y : 3 }). perform ()
await actions . move ({ x : 13 , y : 15 , origin : Origin . POINTER }). perform ()
let result = await driver . findElement ( By . id ( 'absolute-location' )). getText ();
result = result . split ( ', ' );
assert . deepStrictEqual ( Math . abs ( parseInt ( result [ 0 ]) - 6 - 13 ) < 2 , true )
assert . deepStrictEqual ( Math . abs ( parseInt ( result [ 1 ]) - 3 - 15 ) < 2 , true )
});
});
Actions ( driver )
. moveByOffset ( 13 , 15 )
. perform ()
Show full example 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.Rectangle
import org.openqa.selenium.WebElement
import org.openqa.selenium.interactions.Actions
import org.openqa.selenium.interactions.PointerInput
import org.openqa.selenium.interactions.Sequence
import org.openqa.selenium.remote.RemoteWebDriver
import java.time.Duration
import java.util.Collections
class MouseTest : BaseTest () {
@Test
fun clickAndHold () {
driver . get ( "https://www.selenium.dev/selenium/web/mouse_interaction.html" )
val clickable = driver . findElement ( By . id ( "clickable" ))
Actions ( driver )
. clickAndHold ( clickable )
. perform ()
Assertions . assertEquals ( "focused" , driver . findElement ( By . id ( "click-status" )). getText ())
}
@Test
fun clickAndRelease () {
driver . get ( "https://www.selenium.dev/selenium/web/mouse_interaction.html" )
val clickable = driver . findElement ( By . id ( "click" ))
Actions ( driver )
. click ( clickable )
. perform ()
Assertions . assertTrue ( driver . getCurrentUrl () !! . contains ( "resultPage.html" ))
}
@Test
fun rightClick () {
driver . get ( "https://www.selenium.dev/selenium/web/mouse_interaction.html" )
val clickable = driver . findElement ( By . id ( "clickable" ))
Actions ( driver )
. contextClick ( clickable )
. perform ()
Assertions . assertEquals ( "context-clicked" , driver . findElement ( By . id ( "click-status" )). getText ())
}
@Test
fun backClick () {
driver . get ( "https://www.selenium.dev/selenium/web/mouse_interaction.html" )
driver . findElement ( By . id ( "click" )). click ()
Assertions . assertEquals ( driver . getTitle (), "We Arrive Here" )
val mouse = PointerInput ( PointerInput . Kind . MOUSE , "default mouse" )
val actions = Sequence ( mouse , 0 )
. addAction ( mouse . createPointerDown ( PointerInput . MouseButton . BACK . asArg ()))
. addAction ( mouse . createPointerUp ( PointerInput . MouseButton . BACK . asArg ()))
( driver as RemoteWebDriver ). perform ( Collections . singletonList ( actions ))
Assertions . assertEquals ( "BasicMouseInterfaceTest" , driver . getTitle ())
}
@Test
fun forwardClick () {
driver . get ( "https://www.selenium.dev/selenium/web/mouse_interaction.html" )
driver . findElement ( By . id ( "click" )). click ()
driver . navigate (). back ()
Assertions . assertEquals ( driver . getTitle (), "BasicMouseInterfaceTest" )
val mouse = PointerInput ( PointerInput . Kind . MOUSE , "default mouse" )
val actions = Sequence ( mouse , 0 )
. addAction ( mouse . createPointerDown ( PointerInput . MouseButton . FORWARD . asArg ()))
. addAction ( mouse . createPointerUp ( PointerInput . MouseButton . FORWARD . asArg ()))
( driver as RemoteWebDriver ). perform ( Collections . singletonList ( actions ))
Assertions . assertEquals ( "We Arrive Here" , driver . getTitle ())
}
@Test
fun doubleClick () {
driver . get ( "https://www.selenium.dev/selenium/web/mouse_interaction.html" )
val clickable = driver . findElement ( By . id ( "clickable" ))
Actions ( driver )
. doubleClick ( clickable )
. perform ()
Assertions . assertEquals ( "double-clicked" , driver . findElement ( By . id ( "click-status" )). getText ())
}
@Test
fun hovers () {
driver . get ( "https://www.selenium.dev/selenium/web/mouse_interaction.html" )
val hoverable = driver . findElement ( By . id ( "hover" ))
Actions ( driver )
. moveToElement ( hoverable )
. perform ()
Assertions . assertEquals ( "hovered" , driver . findElement ( By . id ( "move-status" )). getText ())
}
@Test
fun moveByOffsetFromElement () {
driver . get ( "https://www.selenium.dev/selenium/web/mouse_interaction.html" )
driver . manage (). window (). fullscreen ()
val tracker = driver . findElement ( By . id ( "mouse-tracker" ))
Actions ( driver )
. moveToElement ( tracker , 8 , 0 )
. perform ()
val result = driver . findElement ( By . id ( "relative-location" )). getText (). split ( ", " )
Assertions . assertTrue ( Math . abs ( Integer . parseInt ( result [ 0 ]) - 100 - 8 ) < 2 )
}
@Test
fun moveByOffsetFromViewport () {
driver . get ( "https://www.selenium.dev/selenium/web/mouse_interaction.html" )
val mouse = PointerInput ( PointerInput . Kind . MOUSE , "default mouse" )
val actions = Sequence ( mouse , 0 )
. addAction ( mouse . createPointerMove ( Duration . ZERO , PointerInput . Origin . viewport (), 8 , 12 ))
( driver as RemoteWebDriver ). perform ( Collections . singletonList ( actions ))
val result = driver . findElement ( By . id ( "absolute-location" )). getText (). split ( ", " )
Assertions . assertTrue ( Math . abs ( Integer . parseInt ( result [ 0 ]) - 8 ) < 2 )
Assertions . assertTrue ( Math . abs ( Integer . parseInt ( result [ 1 ]) - 12 ) < 2 )
}
@Test
fun moveByOffsetFromCurrentPointer () {
driver . get ( "https://www.selenium.dev/selenium/web/mouse_interaction.html" )
val mouse = PointerInput ( PointerInput . Kind . MOUSE , "default mouse" )
val actions = Sequence ( mouse , 0 )
. addAction ( mouse . createPointerMove ( Duration . ZERO , PointerInput . Origin . viewport (), 8 , 11 ))
( driver as RemoteWebDriver ). perform ( Collections . singletonList ( actions ))
Actions ( driver )
. moveByOffset ( 13 , 15 )
. perform ()
val result = driver . findElement ( By . id ( "absolute-location" )). getText (). split ( ", " )
Assertions . assertTrue ( Math . abs ( Integer . parseInt ( result [ 0 ]) - 8 - 13 ) < 2 )
Assertions . assertTrue ( Math . abs ( Integer . parseInt ( result [ 1 ]) - 11 - 15 ) < 2 )
}
@Test
fun dragsToElement () {
driver . get ( "https://www.selenium.dev/selenium/web/mouse_interaction.html" )
val draggable = driver . findElement ( By . id ( "draggable" ))
val droppable = driver . findElement ( By . id ( "droppable" ))
Actions ( driver )
. dragAndDrop ( draggable , droppable )
. perform ()
Assertions . assertEquals ( "dropped" , driver . findElement ( By . id ( "drop-status" )). getText ())
}
@Test
fun dragsByOffset () {
driver . get ( "https://www.selenium.dev/selenium/web/mouse_interaction.html" )
val draggable = driver . findElement ( By . id ( "draggable" ))
val start = draggable . getRect ()
val finish = driver . findElement ( By . id ( "droppable" )). getRect ()
Actions ( driver )
. dragAndDropBy ( draggable , finish . getX () - start . getX (), finish . getY () - start . getY ())
. perform ()
Assertions . assertEquals ( "dropped" , driver . findElement ( By . id ( "drop-status" )). getText ())
}
}
Arrastar e Soltar no Elemento Este método primeiro realiza um clique e mantém pressionado no elemento de origem, move para a localização do elemento de destino e, em seguida, libera o botão do mouse.
Java
Python
CSharp
Ruby
JavaScript
Kotlin WebElement draggable = driver . findElement ( By . id ( "draggable" ));
WebElement droppable = driver . findElement ( By . id ( "droppable" ));
new Actions ( driver )
. dragAndDrop ( draggable , droppable )
. perform ();
Show full example 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.Rectangle ;
import org.openqa.selenium.WebElement ;
import org.openqa.selenium.interactions.Actions ;
import org.openqa.selenium.interactions.PointerInput ;
import org.openqa.selenium.interactions.Sequence ;
import org.openqa.selenium.remote.RemoteWebDriver ;
import java.time.Duration ;
import java.util.Collections ;
public class MouseTest extends BaseChromeTest {
@Test
public void clickAndHold () {
driver . get ( "https://www.selenium.dev/selenium/web/mouse_interaction.html" );
WebElement clickable = driver . findElement ( By . id ( "clickable" ));
new Actions ( driver )
. clickAndHold ( clickable )
. perform ();
Assertions . assertEquals ( "focused" , driver . findElement ( By . id ( "click-status" )). getText ());
}
@Test
public void clickAndRelease () {
driver . get ( "https://www.selenium.dev/selenium/web/mouse_interaction.html" );
WebElement clickable = driver . findElement ( By . id ( "click" ));
new Actions ( driver )
. click ( clickable )
. perform ();
Assertions . assertTrue ( driver . getCurrentUrl (). contains ( "resultPage.html" ));
}
@Test
public void rightClick () {
driver . get ( "https://www.selenium.dev/selenium/web/mouse_interaction.html" );
WebElement clickable = driver . findElement ( By . id ( "clickable" ));
new Actions ( driver )
. contextClick ( clickable )
. perform ();
Assertions . assertEquals ( "context-clicked" , driver . findElement ( By . id ( "click-status" )). getText ());
}
@Test
public void backClick () {
driver . get ( "https://www.selenium.dev/selenium/web/mouse_interaction.html" );
driver . findElement ( By . id ( "click" )). click ();
Assertions . assertEquals ( driver . getTitle (), "We Arrive Here" );
PointerInput mouse = new PointerInput ( PointerInput . Kind . MOUSE , "default mouse" );
Sequence actions = new Sequence ( mouse , 0 )
. addAction ( mouse . createPointerDown ( PointerInput . MouseButton . BACK . asArg ()))
. addAction ( mouse . createPointerUp ( PointerInput . MouseButton . BACK . asArg ()));
(( RemoteWebDriver ) driver ). perform ( Collections . singletonList ( actions ));
Assertions . assertEquals ( "BasicMouseInterfaceTest" , driver . getTitle ());
}
@Test
public void forwardClick () {
driver . get ( "https://www.selenium.dev/selenium/web/mouse_interaction.html" );
driver . findElement ( By . id ( "click" )). click ();
driver . navigate (). back ();
Assertions . assertEquals ( driver . getTitle (), "BasicMouseInterfaceTest" );
PointerInput mouse = new PointerInput ( PointerInput . Kind . MOUSE , "default mouse" );
Sequence actions = new Sequence ( mouse , 0 )
. addAction ( mouse . createPointerDown ( PointerInput . MouseButton . FORWARD . asArg ()))
. addAction ( mouse . createPointerUp ( PointerInput . MouseButton . FORWARD . asArg ()));
(( RemoteWebDriver ) driver ). perform ( Collections . singletonList ( actions ));
Assertions . assertEquals ( "We Arrive Here" , driver . getTitle ());
}
@Test
public void doubleClick () {
driver . get ( "https://www.selenium.dev/selenium/web/mouse_interaction.html" );
WebElement clickable = driver . findElement ( By . id ( "clickable" ));
new Actions ( driver )
. doubleClick ( clickable )
. perform ();
Assertions . assertEquals ( "double-clicked" , driver . findElement ( By . id ( "click-status" )). getText ());
}
@Test
public void hovers () {
driver . get ( "https://www.selenium.dev/selenium/web/mouse_interaction.html" );
WebElement hoverable = driver . findElement ( By . id ( "hover" ));
new Actions ( driver )
. moveToElement ( hoverable )
. perform ();
Assertions . assertEquals ( "hovered" , driver . findElement ( By . id ( "move-status" )). getText ());
}
@Test
public void moveByOffsetFromElement () {
driver . get ( "https://www.selenium.dev/selenium/web/mouse_interaction.html" );
driver . manage (). window (). fullscreen ();
WebElement tracker = driver . findElement ( By . id ( "mouse-tracker" ));
new Actions ( driver )
. moveToElement ( tracker , 8 , 0 )
. perform ();
String [] result = driver . findElement ( By . id ( "relative-location" )). getText (). split ( ", " );
Assertions . assertTrue ( Math . abs ( Integer . parseInt ( result [ 0 ] ) - 100 - 8 ) < 2 );
}
@Test
public void moveByOffsetFromViewport () {
driver . get ( "https://www.selenium.dev/selenium/web/mouse_interaction.html" );
PointerInput mouse = new PointerInput ( PointerInput . Kind . MOUSE , "default mouse" );
Sequence actions = new Sequence ( mouse , 0 )
. addAction ( mouse . createPointerMove ( Duration . ZERO , PointerInput . Origin . viewport (), 8 , 12 ));
(( RemoteWebDriver ) driver ). perform ( Collections . singletonList ( actions ));
String [] result = driver . findElement ( By . id ( "absolute-location" )). getText (). split ( ", " );
Assertions . assertTrue ( Math . abs ( Integer . parseInt ( result [ 0 ] ) - 8 ) < 2 );
Assertions . assertTrue ( Math . abs ( Integer . parseInt ( result [ 1 ] ) - 12 ) < 2 );
}
@Test
public void moveByOffsetFromCurrentPointer () {
driver . get ( "https://www.selenium.dev/selenium/web/mouse_interaction.html" );
PointerInput mouse = new PointerInput ( PointerInput . Kind . MOUSE , "default mouse" );
Sequence actions = new Sequence ( mouse , 0 )
. addAction ( mouse . createPointerMove ( Duration . ZERO , PointerInput . Origin . viewport (), 8 , 11 ));
(( RemoteWebDriver ) driver ). perform ( Collections . singletonList ( actions ));
new Actions ( driver )
. moveByOffset ( 13 , 15 )
. perform ();
String [] result = driver . findElement ( By . id ( "absolute-location" )). getText (). split ( ", " );
Assertions . assertTrue ( Math . abs ( Integer . parseInt ( result [ 0 ] ) - 8 - 13 ) < 2 );
Assertions . assertTrue ( Math . abs ( Integer . parseInt ( result [ 1 ] ) - 11 - 15 ) < 2 );
}
@Test
public void dragsToElement () {
driver . get ( "https://www.selenium.dev/selenium/web/mouse_interaction.html" );
WebElement draggable = driver . findElement ( By . id ( "draggable" ));
WebElement droppable = driver . findElement ( By . id ( "droppable" ));
new Actions ( driver )
. dragAndDrop ( draggable , droppable )
. perform ();
Assertions . assertEquals ( "dropped" , driver . findElement ( By . id ( "drop-status" )). getText ());
}
@Test
public void dragsByOffset () {
driver . get ( "https://www.selenium.dev/selenium/web/mouse_interaction.html" );
WebElement draggable = driver . findElement ( By . id ( "draggable" ));
Rectangle start = draggable . getRect ();
Rectangle finish = driver . findElement ( By . id ( "droppable" )). getRect ();
new Actions ( driver )
. dragAndDropBy ( draggable , finish . getX () - start . getX (), finish . getY () - start . getY ())
. perform ();
Assertions . assertEquals ( "dropped" , driver . findElement ( By . id ( "drop-status" )). getText ());
}
}
draggable = driver . find_element ( By . ID , "draggable" )
droppable = driver . find_element ( By . ID , "droppable" )
ActionChains ( driver ) \
. drag_and_drop ( draggable , droppable ) \
. perform ()
Show full example import pytest
from time import sleep
from selenium.webdriver import ActionChains
from selenium.webdriver.common.actions.action_builder import ActionBuilder
from selenium.webdriver.common.actions.mouse_button import MouseButton
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
def test_click_and_hold ( driver ):
driver . get ( 'https://selenium.dev/selenium/web/mouse_interaction.html' )
clickable = driver . find_element ( By . ID , "clickable" )
ActionChains ( driver ) \
. click_and_hold ( clickable ) \
. perform ()
sleep ( 0.5 )
assert driver . find_element ( By . ID , "click-status" ) . text == "focused"
def test_click_and_release ( driver ):
driver . get ( 'https://selenium.dev/selenium/web/mouse_interaction.html' )
clickable = driver . find_element ( By . ID , "click" )
ActionChains ( driver ) \
. click ( clickable ) \
. perform ()
assert "resultPage.html" in driver . current_url
def test_right_click ( driver ):
driver . get ( 'https://selenium.dev/selenium/web/mouse_interaction.html' )
clickable = driver . find_element ( By . ID , "clickable" )
ActionChains ( driver ) \
. context_click ( clickable ) \
. perform ()
sleep ( 0.5 )
assert driver . find_element ( By . ID , "click-status" ) . text == "context-clicked"
def test_back_click_ab ( driver ):
driver . get ( 'https://selenium.dev/selenium/web/mouse_interaction.html' )
driver . find_element ( By . ID , "click" ) . click ()
assert driver . title == "We Arrive Here"
action = ActionBuilder ( driver )
action . pointer_action . pointer_down ( MouseButton . BACK )
action . pointer_action . pointer_up ( MouseButton . BACK )
action . perform ()
assert driver . title == "BasicMouseInterfaceTest"
def test_forward_click_ab ( driver ):
driver . get ( 'https://selenium.dev/selenium/web/mouse_interaction.html' )
driver . find_element ( By . ID , "click" ) . click ()
driver . back ()
assert driver . title == "BasicMouseInterfaceTest"
action = ActionBuilder ( driver )
action . pointer_action . pointer_down ( MouseButton . FORWARD )
action . pointer_action . pointer_up ( MouseButton . FORWARD )
action . perform ()
assert driver . title == "We Arrive Here"
def test_double_click ( driver ):
driver . get ( 'https://selenium.dev/selenium/web/mouse_interaction.html' )
clickable = driver . find_element ( By . ID , "clickable" )
ActionChains ( driver ) \
. double_click ( clickable ) \
. perform ()
assert driver . find_element ( By . ID , "click-status" ) . text == "double-clicked"
def test_hover ( driver ):
driver . get ( 'https://selenium.dev/selenium/web/mouse_interaction.html' )
hoverable = driver . find_element ( By . ID , "hover" )
ActionChains ( driver ) \
. move_to_element ( hoverable ) \
. perform ()
assert driver . find_element ( By . ID , "move-status" ) . text == "hovered"
def test_move_by_offset_from_element ( driver ):
driver . get ( 'https://selenium.dev/selenium/web/mouse_interaction.html' )
mouse_tracker = driver . find_element ( By . ID , "mouse-tracker" )
ActionChains ( driver ) \
. move_to_element_with_offset ( mouse_tracker , 8 , 0 ) \
. perform ()
coordinates = driver . find_element ( By . ID , "relative-location" ) . text . split ( ", " )
assert abs ( int ( coordinates [ 0 ]) - 100 - 8 ) < 2
def test_move_by_offset_from_viewport_origin_ab ( driver ):
driver . get ( 'https://selenium.dev/selenium/web/mouse_interaction.html' )
WebDriverWait ( driver , 10 ) . until ( EC . presence_of_element_located (( By . ID , "absolute-location" )))
action = ActionBuilder ( driver )
action . pointer_action . move_to_location ( 8 , 0 )
action . perform ()
coordinates = driver . find_element ( By . ID , "absolute-location" ) . text . split ( ", " )
assert abs ( int ( coordinates [ 0 ]) - 8 ) < 2
def test_move_by_offset_from_current_pointer_ab ( driver ):
driver . get ( 'https://selenium.dev/selenium/web/mouse_interaction.html' )
action = ActionBuilder ( driver )
action . pointer_action . move_to_location ( 6 , 3 )
action . perform ()
ActionChains ( driver ) \
. move_by_offset ( 13 , 15 ) \
. perform ()
coordinates = driver . find_element ( By . ID , "absolute-location" ) . text . split ( ", " )
assert abs ( int ( coordinates [ 0 ]) - 6 - 13 ) < 2
assert abs ( int ( coordinates [ 1 ]) - 3 - 15 ) < 2
def test_drag_and_drop_onto_element ( driver ):
driver . get ( 'https://selenium.dev/selenium/web/mouse_interaction.html' )
draggable = driver . find_element ( By . ID , "draggable" )
droppable = driver . find_element ( By . ID , "droppable" )
ActionChains ( driver ) \
. drag_and_drop ( draggable , droppable ) \
. perform ()
assert driver . find_element ( By . ID , "drop-status" ) . text == "dropped"
def test_drag_and_drop_by_offset ( driver ):
driver . get ( 'https://selenium.dev/selenium/web/mouse_interaction.html' )
draggable = driver . find_element ( By . ID , "draggable" )
start = draggable . location
finish = driver . find_element ( By . ID , "droppable" ) . location
ActionChains ( driver ) \
. drag_and_drop_by_offset ( draggable , finish [ 'x' ] - start [ 'x' ], finish [ 'y' ] - start [ 'y' ]) \
. perform ()
assert driver . find_element ( By . ID , "drop-status" ) . text == "dropped"
IWebElement draggable = driver . FindElement ( By . Id ( "draggable" ));
IWebElement droppable = driver . FindElement ( By . Id ( "droppable" ));
new Actions ( driver )
. DragAndDrop ( draggable , droppable )
. Perform ();
Show full example using System ;
using System.Drawing ;
using Microsoft.VisualStudio.TestTools.UnitTesting ;
using OpenQA.Selenium ;
using OpenQA.Selenium.Interactions ;
namespace SeleniumDocs.ActionsAPI
{
[TestClass]
public class MouseTest : BaseChromeTest
{
[TestMethod]
public void ClickAndHold ()
{
driver . Url = "https://selenium.dev/selenium/web/mouse_interaction.html" ;
IWebElement clickable = driver . FindElement ( By . Id ( "clickable" ));
new Actions ( driver )
. ClickAndHold ( clickable )
. Perform ();
Assert . AreEqual ( "focused" , driver . FindElement ( By . Id ( "click-status" )). Text );
}
[TestMethod]
public void ClickAndRelease ()
{
driver . Url = "https://selenium.dev/selenium/web/mouse_interaction.html" ;
IWebElement clickable = driver . FindElement ( By . Id ( "click" ));
new Actions ( driver )
. Click ( clickable )
. Perform ();
Assert . IsTrue ( driver . Url . Contains ( "resultPage.html" ));
}
[TestMethod]
public void RightClick ()
{
driver . Url = "https://selenium.dev/selenium/web/mouse_interaction.html" ;
IWebElement clickable = driver . FindElement ( By . Id ( "clickable" ));
new Actions ( driver )
. ContextClick ( clickable )
. Perform ();
Assert . AreEqual ( "context-clicked" , driver . FindElement ( By . Id ( "click-status" )). Text );
}
[TestMethod]
public void BackClick ()
{
driver . Url = "https://selenium.dev/selenium/web/mouse_interaction.html" ;
driver . FindElement ( By . Id ( "click" )). Click ();
Assert . AreEqual ( "We Arrive Here" , driver . Title );
ActionBuilder actionBuilder = new ActionBuilder ();
PointerInputDevice mouse = new PointerInputDevice ( PointerKind . Mouse , "default mouse" );
actionBuilder . AddAction ( mouse . CreatePointerDown ( MouseButton . Back ));
actionBuilder . AddAction ( mouse . CreatePointerUp ( MouseButton . Back ));
(( IActionExecutor ) driver ). PerformActions ( actionBuilder . ToActionSequenceList ());
Assert . AreEqual ( "BasicMouseInterfaceTest" , driver . Title );
}
[TestMethod]
public void ForwardClick ()
{
driver . Url = "https://selenium.dev/selenium/web/mouse_interaction.html" ;
driver . FindElement ( By . Id ( "click" )). Click ();
driver . Navigate (). Back ();
Assert . AreEqual ( "BasicMouseInterfaceTest" , driver . Title );
ActionBuilder actionBuilder = new ActionBuilder ();
PointerInputDevice mouse = new PointerInputDevice ( PointerKind . Mouse , "default mouse" );
actionBuilder . AddAction ( mouse . CreatePointerDown ( MouseButton . Forward ));
actionBuilder . AddAction ( mouse . CreatePointerUp ( MouseButton . Forward ));
(( IActionExecutor ) driver ). PerformActions ( actionBuilder . ToActionSequenceList ());
Assert . AreEqual ( "We Arrive Here" , driver . Title );
}
[TestMethod]
public void DoubleClick ()
{
driver . Url = "https://selenium.dev/selenium/web/mouse_interaction.html" ;
IWebElement clickable = driver . FindElement ( By . Id ( "clickable" ));
new Actions ( driver )
. DoubleClick ( clickable )
. Perform ();
Assert . AreEqual ( "double-clicked" , driver . FindElement ( By . Id ( "click-status" )). Text );
}
[TestMethod]
public void Hovers ()
{
driver . Url = "https://selenium.dev/selenium/web/mouse_interaction.html" ;
IWebElement hoverable = driver . FindElement ( By . Id ( "hover" ));
new Actions ( driver )
. MoveToElement ( hoverable )
. Perform ();
Assert . AreEqual ( "hovered" , driver . FindElement ( By . Id ( "move-status" )). Text );
}
[TestMethod]
[Obsolete("Obsolete")]
public void MoveByOffsetFromTopLeftOfElement ()
{
driver . Url = "https://selenium.dev/selenium/web/mouse_interaction.html" ;
IWebElement tracker = driver . FindElement ( By . Id ( "mouse-tracker" ));
new Actions ( driver )
. MoveToElement ( tracker , 8 , 0 )
. Perform ();
string [] result = driver . FindElement ( By . Id ( "relative-location" )). Text . Split ( ", " );
Assert . IsTrue ( Math . Abs ( int . Parse ( result [ 0 ]) - 100 - 8 ) < 2 );
}
[TestMethod]
public void MoveByOffsetFromCenterOfElement ()
{
driver . Url = "https://selenium.dev/selenium/web/mouse_interaction.html" ;
IWebElement tracker = driver . FindElement ( By . Id ( "mouse-tracker" ));
new Actions ( driver )
. MoveToElement ( tracker , 8 , 0 )
. Perform ();
string [] result = driver . FindElement ( By . Id ( "relative-location" )). Text . Split ( ", " );
Assert . IsTrue ( Math . Abs ( int . Parse ( result [ 0 ]) - 100 - 8 ) < 2 );
}
[TestMethod]
public void MoveByOffsetFromViewport ()
{
driver . Url = "https://selenium.dev/selenium/web/mouse_interaction.html" ;
ActionBuilder actionBuilder = new ActionBuilder ();
PointerInputDevice mouse = new PointerInputDevice ( PointerKind . Mouse , "default mouse" );
actionBuilder . AddAction ( mouse . CreatePointerMove ( CoordinateOrigin . Viewport ,
8 , 0 , TimeSpan . Zero ));
(( IActionExecutor ) driver ). PerformActions ( actionBuilder . ToActionSequenceList ());
string [] result = driver . FindElement ( By . Id ( "absolute-location" )). Text . Split ( ", " );
Assert . IsTrue ( Math . Abs ( int . Parse ( result [ 0 ]) - 8 ) < 2 );
}
[TestMethod]
public void MoveByOffsetFromCurrentPointerLocation ()
{
driver . Url = "https://selenium.dev/selenium/web/mouse_interaction.html" ;
ActionBuilder actionBuilder = new ActionBuilder ();
PointerInputDevice mouse = new PointerInputDevice ( PointerKind . Mouse , "default mouse" );
actionBuilder . AddAction ( mouse . CreatePointerMove ( CoordinateOrigin . Viewport ,
8 , 12 , TimeSpan . Zero ));
(( IActionExecutor ) driver ). PerformActions ( actionBuilder . ToActionSequenceList ());
new Actions ( driver )
. MoveByOffset ( 13 , 15 )
. Perform ();
string [] result = driver . FindElement ( By . Id ( "absolute-location" )). Text . Split ( ", " );
Assert . IsTrue ( Math . Abs ( int . Parse ( result [ 0 ]) - 8 - 13 ) < 2 );
Assert . IsTrue ( Math . Abs ( int . Parse ( result [ 1 ]) - 12 - 15 ) < 2 );
}
[TestMethod]
public void DragToElement ()
{
driver . Url = "https://selenium.dev/selenium/web/mouse_interaction.html" ;
IWebElement draggable = driver . FindElement ( By . Id ( "draggable" ));
IWebElement droppable = driver . FindElement ( By . Id ( "droppable" ));
new Actions ( driver )
. DragAndDrop ( draggable , droppable )
. Perform ();
Assert . AreEqual ( "dropped" , driver . FindElement ( By . Id ( "drop-status" )). Text );
}
[TestMethod]
public void DragByOffset ()
{
driver . Url = "https://selenium.dev/selenium/web/mouse_interaction.html" ;
IWebElement draggable = driver . FindElement ( By . Id ( "draggable" ));
Point start = draggable . Location ;
Point finish = driver . FindElement ( By . Id ( "droppable" )). Location ;
new Actions ( driver )
. DragAndDropToOffset ( draggable , finish . X - start . X , finish . Y - start . Y )
. Perform ();
Assert . AreEqual ( "dropped" , driver . FindElement ( By . Id ( "drop-status" )). Text );
}
}
}
draggable = driver . find_element ( id : 'draggable' )
droppable = driver . find_element ( id : 'droppable' )
driver . action
. drag_and_drop ( draggable , droppable )
. perform
Show full example # frozen_string_literal: true
require 'spec_helper'
RSpec . describe 'Mouse' do
let ( :driver ) { start_session }
it 'click and hold' do
driver . get 'https://www.selenium.dev/selenium/web/mouse_interaction.html'
clickable = driver . find_element ( id : 'clickable' )
driver . action
. click_and_hold ( clickable )
. perform
expect ( driver . find_element ( id : 'click-status' ) . text ) . to eq 'focused'
end
it 'click and release' do
driver . get 'https://www.selenium.dev/selenium/web/mouse_interaction.html'
clickable = driver . find_element ( id : 'click' )
driver . action
. click ( clickable )
. perform
expect ( driver . current_url ) . to include 'resultPage.html'
end
describe 'alternate button clicks' do
it 'right click' do
driver . get 'https://www.selenium.dev/selenium/web/mouse_interaction.html'
clickable = driver . find_element ( id : 'clickable' )
driver . action
. context_click ( clickable )
. perform
expect ( driver . find_element ( id : 'click-status' ) . text ) . to eq 'context-clicked'
end
it 'back click' do
driver . get 'https://www.selenium.dev/selenium/web/mouse_interaction.html'
driver . find_element ( id : 'click' ) . click
expect ( driver . title ) . to eq ( 'We Arrive Here' )
driver . action
. pointer_down ( :back )
. pointer_up ( :back )
. perform
expect ( driver . title ) . to eq ( 'BasicMouseInterfaceTest' )
end
it 'forward click' do
driver . get 'https://www.selenium.dev/selenium/web/mouse_interaction.html'
driver . find_element ( id : 'click' ) . click
driver . navigate . back
expect ( driver . title ) . to eq ( 'BasicMouseInterfaceTest' )
driver . action
. pointer_down ( :forward )
. pointer_up ( :forward )
. perform
expect ( driver . title ) . to eq ( 'We Arrive Here' )
end
end
it 'double click' do
driver . get 'https://www.selenium.dev/selenium/web/mouse_interaction.html'
clickable = driver . find_element ( id : 'clickable' )
driver . action
. double_click ( clickable )
. perform
expect ( driver . find_element ( id : 'click-status' ) . text ) . to eq 'double-clicked'
end
it 'hovers' do
driver . get 'https://www.selenium.dev/selenium/web/mouse_interaction.html'
hoverable = driver . find_element ( id : 'hover' )
driver . action
. move_to ( hoverable )
. perform
expect ( driver . find_element ( id : 'move-status' ) . text ) . to eq 'hovered'
end
describe 'move by offset' do
it 'offset from element' do
driver . get 'https://www.selenium.dev/selenium/web/mouse_interaction.html'
driver . action . scroll_to ( driver . find_element ( id : 'bottom' )) . perform
mouse_tracker = driver . find_element ( id : 'mouse-tracker' )
driver . action
. move_to ( mouse_tracker , 8 , 11 )
. perform
rect = mouse_tracker . rect
center_x = rect . width / 2
center_y = rect . height / 2
x_coord , y_coord = driver . find_element ( id : 'relative-location' ) . text . split ( ',' ) . map ( & :to_i )
expect ( x_coord ) . to be_within ( 1 ) . of ( center_x + 8 )
expect ( y_coord ) . to be_within ( 1 ) . of ( center_y + 11 )
end
it 'offset from viewport' do
driver . get 'https://www.selenium.dev/selenium/web/mouse_interaction.html'
driver . action
. move_to_location ( 8 , 12 )
. perform
x_coord , y_coord = driver . find_element ( id : 'absolute-location' ) . text . split ( ',' ) . map ( & :to_i )
expect ( x_coord ) . to be_within ( 1 ) . of ( 8 )
expect ( y_coord ) . to be_within ( 1 ) . of ( 12 )
end
it 'offset from current pointer location' do
driver . get 'https://www.selenium.dev/selenium/web/mouse_interaction.html'
driver . action . move_to_location ( 8 , 11 ) . perform
driver . action
. move_by ( 13 , 15 )
. perform
x_coord , y_coord = driver . find_element ( id : 'absolute-location' ) . text . split ( ',' ) . map ( & :to_i )
expect ( x_coord ) . to be_within ( 1 ) . of ( 8 + 13 )
expect ( y_coord ) . to be_within ( 1 ) . of ( 11 + 15 )
end
end
it 'drags to another element' do
driver . get 'https://www.selenium.dev/selenium/web/mouse_interaction.html'
draggable = driver . find_element ( id : 'draggable' )
droppable = driver . find_element ( id : 'droppable' )
driver . action
. drag_and_drop ( draggable , droppable )
. perform
expect ( driver . find_element ( id : 'drop-status' ) . text ) . to include ( 'dropped' )
end
it 'drags by an offset' do
driver . get 'https://www.selenium.dev/selenium/web/mouse_interaction.html'
draggable = driver . find_element ( id : 'draggable' )
start = draggable . rect
finish = driver . find_element ( id : 'droppable' ) . rect
driver . action
. drag_and_drop_by ( draggable , finish . x - start . x , finish . y - start . y )
. perform
expect ( driver . find_element ( id : 'drop-status' ) . text ) . to include ( 'dropped' )
end
end
const draggable = driver . findElement ( By . id ( "draggable" ));
const droppable = await driver . findElement ( By . id ( "droppable" ));
const actions = driver . actions ({ async : true });
await actions . dragAndDrop ( draggable , droppable ). perform ();
Show full example const { By , Builder } = require ( 'selenium-webdriver' );
const assert = require ( 'assert' );
describe ( 'Drag and Drop' , function () {
let driver ;
before ( async function () {
driver = new Builder (). forBrowser ( 'chrome' ). build ();
});
after ( async () => await driver . quit ());
it ( 'By Offset' , async function () {
await driver . get ( 'https://www.selenium.dev/selenium/web/mouse_interaction.html' );
const draggable = driver . findElement ( By . id ( "draggable" ));
let start = await draggable . getRect ();
let finish = await driver . findElement ( By . id ( "droppable" )). getRect ();
const actions = driver . actions ({ async : true });
await actions . dragAndDrop ( draggable , { x : finish . x - start . x , y : finish . y - start . y }). perform ();
let result = await driver . findElement ( By . id ( "drop-status" )). getText ();
assert . deepStrictEqual ( 'dropped' , result )
});
it ( 'Onto Element' , async function () {
await driver . get ( 'https://www.selenium.dev/selenium/web/mouse_interaction.html' );
const draggable = driver . findElement ( By . id ( "draggable" ));
const droppable = await driver . findElement ( By . id ( "droppable" ));
const actions = driver . actions ({ async : true });
await actions . dragAndDrop ( draggable , droppable ). perform ();
let result = await driver . findElement ( By . id ( "drop-status" )). getText ();
assert . deepStrictEqual ( 'dropped' , result )
});
});
val draggable = driver . findElement ( By . id ( "draggable" ))
val droppable = driver . findElement ( By . id ( "droppable" ))
Actions ( driver )
. dragAndDrop ( draggable , droppable )
. perform ()
Show full example 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.Rectangle
import org.openqa.selenium.WebElement
import org.openqa.selenium.interactions.Actions
import org.openqa.selenium.interactions.PointerInput
import org.openqa.selenium.interactions.Sequence
import org.openqa.selenium.remote.RemoteWebDriver
import java.time.Duration
import java.util.Collections
class MouseTest : BaseTest () {
@Test
fun clickAndHold () {
driver . get ( "https://www.selenium.dev/selenium/web/mouse_interaction.html" )
val clickable = driver . findElement ( By . id ( "clickable" ))
Actions ( driver )
. clickAndHold ( clickable )
. perform ()
Assertions . assertEquals ( "focused" , driver . findElement ( By . id ( "click-status" )). getText ())
}
@Test
fun clickAndRelease () {
driver . get ( "https://www.selenium.dev/selenium/web/mouse_interaction.html" )
val clickable = driver . findElement ( By . id ( "click" ))
Actions ( driver )
. click ( clickable )
. perform ()
Assertions . assertTrue ( driver . getCurrentUrl () !! . contains ( "resultPage.html" ))
}
@Test
fun rightClick () {
driver . get ( "https://www.selenium.dev/selenium/web/mouse_interaction.html" )
val clickable = driver . findElement ( By . id ( "clickable" ))
Actions ( driver )
. contextClick ( clickable )
. perform ()
Assertions . assertEquals ( "context-clicked" , driver . findElement ( By . id ( "click-status" )). getText ())
}
@Test
fun backClick () {
driver . get ( "https://www.selenium.dev/selenium/web/mouse_interaction.html" )
driver . findElement ( By . id ( "click" )). click ()
Assertions . assertEquals ( driver . getTitle (), "We Arrive Here" )
val mouse = PointerInput ( PointerInput . Kind . MOUSE , "default mouse" )
val actions = Sequence ( mouse , 0 )
. addAction ( mouse . createPointerDown ( PointerInput . MouseButton . BACK . asArg ()))
. addAction ( mouse . createPointerUp ( PointerInput . MouseButton . BACK . asArg ()))
( driver as RemoteWebDriver ). perform ( Collections . singletonList ( actions ))
Assertions . assertEquals ( "BasicMouseInterfaceTest" , driver . getTitle ())
}
@Test
fun forwardClick () {
driver . get ( "https://www.selenium.dev/selenium/web/mouse_interaction.html" )
driver . findElement ( By . id ( "click" )). click ()
driver . navigate (). back ()
Assertions . assertEquals ( driver . getTitle (), "BasicMouseInterfaceTest" )
val mouse = PointerInput ( PointerInput . Kind . MOUSE , "default mouse" )
val actions = Sequence ( mouse , 0 )
. addAction ( mouse . createPointerDown ( PointerInput . MouseButton . FORWARD . asArg ()))
. addAction ( mouse . createPointerUp ( PointerInput . MouseButton . FORWARD . asArg ()))
( driver as RemoteWebDriver ). perform ( Collections . singletonList ( actions ))
Assertions . assertEquals ( "We Arrive Here" , driver . getTitle ())
}
@Test
fun doubleClick () {
driver . get ( "https://www.selenium.dev/selenium/web/mouse_interaction.html" )
val clickable = driver . findElement ( By . id ( "clickable" ))
Actions ( driver )
. doubleClick ( clickable )
. perform ()
Assertions . assertEquals ( "double-clicked" , driver . findElement ( By . id ( "click-status" )). getText ())
}
@Test
fun hovers () {
driver . get ( "https://www.selenium.dev/selenium/web/mouse_interaction.html" )
val hoverable = driver . findElement ( By . id ( "hover" ))
Actions ( driver )
. moveToElement ( hoverable )
. perform ()
Assertions . assertEquals ( "hovered" , driver . findElement ( By . id ( "move-status" )). getText ())
}
@Test
fun moveByOffsetFromElement () {
driver . get ( "https://www.selenium.dev/selenium/web/mouse_interaction.html" )
driver . manage (). window (). fullscreen ()
val tracker = driver . findElement ( By . id ( "mouse-tracker" ))
Actions ( driver )
. moveToElement ( tracker , 8 , 0 )
. perform ()
val result = driver . findElement ( By . id ( "relative-location" )). getText (). split ( ", " )
Assertions . assertTrue ( Math . abs ( Integer . parseInt ( result [ 0 ]) - 100 - 8 ) < 2 )
}
@Test
fun moveByOffsetFromViewport () {
driver . get ( "https://www.selenium.dev/selenium/web/mouse_interaction.html" )
val mouse = PointerInput ( PointerInput . Kind . MOUSE , "default mouse" )
val actions = Sequence ( mouse , 0 )
. addAction ( mouse . createPointerMove ( Duration . ZERO , PointerInput . Origin . viewport (), 8 , 12 ))
( driver as RemoteWebDriver ). perform ( Collections . singletonList ( actions ))
val result = driver . findElement ( By . id ( "absolute-location" )). getText (). split ( ", " )
Assertions . assertTrue ( Math . abs ( Integer . parseInt ( result [ 0 ]) - 8 ) < 2 )
Assertions . assertTrue ( Math . abs ( Integer . parseInt ( result [ 1 ]) - 12 ) < 2 )
}
@Test
fun moveByOffsetFromCurrentPointer () {
driver . get ( "https://www.selenium.dev/selenium/web/mouse_interaction.html" )
val mouse = PointerInput ( PointerInput . Kind . MOUSE , "default mouse" )
val actions = Sequence ( mouse , 0 )
. addAction ( mouse . createPointerMove ( Duration . ZERO , PointerInput . Origin . viewport (), 8 , 11 ))
( driver as RemoteWebDriver ). perform ( Collections . singletonList ( actions ))
Actions ( driver )
. moveByOffset ( 13 , 15 )
. perform ()
val result = driver . findElement ( By . id ( "absolute-location" )). getText (). split ( ", " )
Assertions . assertTrue ( Math . abs ( Integer . parseInt ( result [ 0 ]) - 8 - 13 ) < 2 )
Assertions . assertTrue ( Math . abs ( Integer . parseInt ( result [ 1 ]) - 11 - 15 ) < 2 )
}
@Test
fun dragsToElement () {
driver . get ( "https://www.selenium.dev/selenium/web/mouse_interaction.html" )
val draggable = driver . findElement ( By . id ( "draggable" ))
val droppable = driver . findElement ( By . id ( "droppable" ))
Actions ( driver )
. dragAndDrop ( draggable , droppable )
. perform ()
Assertions . assertEquals ( "dropped" , driver . findElement ( By . id ( "drop-status" )). getText ())
}
@Test
fun dragsByOffset () {
driver . get ( "https://www.selenium.dev/selenium/web/mouse_interaction.html" )
val draggable = driver . findElement ( By . id ( "draggable" ))
val start = draggable . getRect ()
val finish = driver . findElement ( By . id ( "droppable" )). getRect ()
Actions ( driver )
. dragAndDropBy ( draggable , finish . getX () - start . getX (), finish . getY () - start . getY ())
. perform ()
Assertions . assertEquals ( "dropped" , driver . findElement ( By . id ( "drop-status" )). getText ())
}
}
Arrastar e Soltar pelo Deslocamento Este método primeiro realiza um clique e mantém pressionado no elemento de origem, move para o deslocamento fornecido e, em seguida, libera o botão do mouse.
Java
Python
CSharp
Ruby
JavaScript
Kotlin WebElement draggable = driver . findElement ( By . id ( "draggable" ));
Rectangle start = draggable . getRect ();
Rectangle finish = driver . findElement ( By . id ( "droppable" )). getRect ();
new Actions ( driver )
. dragAndDropBy ( draggable , finish . getX () - start . getX (), finish . getY () - start . getY ())
. perform ();
Show full example 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.Rectangle ;
import org.openqa.selenium.WebElement ;
import org.openqa.selenium.interactions.Actions ;
import org.openqa.selenium.interactions.PointerInput ;
import org.openqa.selenium.interactions.Sequence ;
import org.openqa.selenium.remote.RemoteWebDriver ;
import java.time.Duration ;
import java.util.Collections ;
public class MouseTest extends BaseChromeTest {
@Test
public void clickAndHold () {
driver . get ( "https://www.selenium.dev/selenium/web/mouse_interaction.html" );
WebElement clickable = driver . findElement ( By . id ( "clickable" ));
new Actions ( driver )
. clickAndHold ( clickable )
. perform ();
Assertions . assertEquals ( "focused" , driver . findElement ( By . id ( "click-status" )). getText ());
}
@Test
public void clickAndRelease () {
driver . get ( "https://www.selenium.dev/selenium/web/mouse_interaction.html" );
WebElement clickable = driver . findElement ( By . id ( "click" ));
new Actions ( driver )
. click ( clickable )
. perform ();
Assertions . assertTrue ( driver . getCurrentUrl (). contains ( "resultPage.html" ));
}
@Test
public void rightClick () {
driver . get ( "https://www.selenium.dev/selenium/web/mouse_interaction.html" );
WebElement clickable = driver . findElement ( By . id ( "clickable" ));
new Actions ( driver )
. contextClick ( clickable )
. perform ();
Assertions . assertEquals ( "context-clicked" , driver . findElement ( By . id ( "click-status" )). getText ());
}
@Test
public void backClick () {
driver . get ( "https://www.selenium.dev/selenium/web/mouse_interaction.html" );
driver . findElement ( By . id ( "click" )). click ();
Assertions . assertEquals ( driver . getTitle (), "We Arrive Here" );
PointerInput mouse = new PointerInput ( PointerInput . Kind . MOUSE , "default mouse" );
Sequence actions = new Sequence ( mouse , 0 )
. addAction ( mouse . createPointerDown ( PointerInput . MouseButton . BACK . asArg ()))
. addAction ( mouse . createPointerUp ( PointerInput . MouseButton . BACK . asArg ()));
(( RemoteWebDriver ) driver ). perform ( Collections . singletonList ( actions ));
Assertions . assertEquals ( "BasicMouseInterfaceTest" , driver . getTitle ());
}
@Test
public void forwardClick () {
driver . get ( "https://www.selenium.dev/selenium/web/mouse_interaction.html" );
driver . findElement ( By . id ( "click" )). click ();
driver . navigate (). back ();
Assertions . assertEquals ( driver . getTitle (), "BasicMouseInterfaceTest" );
PointerInput mouse = new PointerInput ( PointerInput . Kind . MOUSE , "default mouse" );
Sequence actions = new Sequence ( mouse , 0 )
. addAction ( mouse . createPointerDown ( PointerInput . MouseButton . FORWARD . asArg ()))
. addAction ( mouse . createPointerUp ( PointerInput . MouseButton . FORWARD . asArg ()));
(( RemoteWebDriver ) driver ). perform ( Collections . singletonList ( actions ));
Assertions . assertEquals ( "We Arrive Here" , driver . getTitle ());
}
@Test
public void doubleClick () {
driver . get ( "https://www.selenium.dev/selenium/web/mouse_interaction.html" );
WebElement clickable = driver . findElement ( By . id ( "clickable" ));
new Actions ( driver )
. doubleClick ( clickable )
. perform ();
Assertions . assertEquals ( "double-clicked" , driver . findElement ( By . id ( "click-status" )). getText ());
}
@Test
public void hovers () {
driver . get ( "https://www.selenium.dev/selenium/web/mouse_interaction.html" );
WebElement hoverable = driver . findElement ( By . id ( "hover" ));
new Actions ( driver )
. moveToElement ( hoverable )
. perform ();
Assertions . assertEquals ( "hovered" , driver . findElement ( By . id ( "move-status" )). getText ());
}
@Test
public void moveByOffsetFromElement () {
driver . get ( "https://www.selenium.dev/selenium/web/mouse_interaction.html" );
driver . manage (). window (). fullscreen ();
WebElement tracker = driver . findElement ( By . id ( "mouse-tracker" ));
new Actions ( driver )
. moveToElement ( tracker , 8 , 0 )
. perform ();
String [] result = driver . findElement ( By . id ( "relative-location" )). getText (). split ( ", " );
Assertions . assertTrue ( Math . abs ( Integer . parseInt ( result [ 0 ] ) - 100 - 8 ) < 2 );
}
@Test
public void moveByOffsetFromViewport () {
driver . get ( "https://www.selenium.dev/selenium/web/mouse_interaction.html" );
PointerInput mouse = new PointerInput ( PointerInput . Kind . MOUSE , "default mouse" );
Sequence actions = new Sequence ( mouse , 0 )
. addAction ( mouse . createPointerMove ( Duration . ZERO , PointerInput . Origin . viewport (), 8 , 12 ));
(( RemoteWebDriver ) driver ). perform ( Collections . singletonList ( actions ));
String [] result = driver . findElement ( By . id ( "absolute-location" )). getText (). split ( ", " );
Assertions . assertTrue ( Math . abs ( Integer . parseInt ( result [ 0 ] ) - 8 ) < 2 );
Assertions . assertTrue ( Math . abs ( Integer . parseInt ( result [ 1 ] ) - 12 ) < 2 );
}
@Test
public void moveByOffsetFromCurrentPointer () {
driver . get ( "https://www.selenium.dev/selenium/web/mouse_interaction.html" );
PointerInput mouse = new PointerInput ( PointerInput . Kind . MOUSE , "default mouse" );
Sequence actions = new Sequence ( mouse , 0 )
. addAction ( mouse . createPointerMove ( Duration . ZERO , PointerInput . Origin . viewport (), 8 , 11 ));
(( RemoteWebDriver ) driver ). perform ( Collections . singletonList ( actions ));
new Actions ( driver )
. moveByOffset ( 13 , 15 )
. perform ();
String [] result = driver . findElement ( By . id ( "absolute-location" )). getText (). split ( ", " );
Assertions . assertTrue ( Math . abs ( Integer . parseInt ( result [ 0 ] ) - 8 - 13 ) < 2 );
Assertions . assertTrue ( Math . abs ( Integer . parseInt ( result [ 1 ] ) - 11 - 15 ) < 2 );
}
@Test
public void dragsToElement () {
driver . get ( "https://www.selenium.dev/selenium/web/mouse_interaction.html" );
WebElement draggable = driver . findElement ( By . id ( "draggable" ));
WebElement droppable = driver . findElement ( By . id ( "droppable" ));
new Actions ( driver )
. dragAndDrop ( draggable , droppable )
. perform ();
Assertions . assertEquals ( "dropped" , driver . findElement ( By . id ( "drop-status" )). getText ());
}
@Test
public void dragsByOffset () {
driver . get ( "https://www.selenium.dev/selenium/web/mouse_interaction.html" );
WebElement draggable = driver . findElement ( By . id ( "draggable" ));
Rectangle start = draggable . getRect ();
Rectangle finish = driver . findElement ( By . id ( "droppable" )). getRect ();
new Actions ( driver )
. dragAndDropBy ( draggable , finish . getX () - start . getX (), finish . getY () - start . getY ())
. perform ();
Assertions . assertEquals ( "dropped" , driver . findElement ( By . id ( "drop-status" )). getText ());
}
}
draggable = driver . find_element ( By . ID , "draggable" )
start = draggable . location
finish = driver . find_element ( By . ID , "droppable" ) . location
ActionChains ( driver ) \
. drag_and_drop_by_offset ( draggable , finish [ 'x' ] - start [ 'x' ], finish [ 'y' ] - start [ 'y' ]) \
. perform ()
Show full example import pytest
from time import sleep
from selenium.webdriver import ActionChains
from selenium.webdriver.common.actions.action_builder import ActionBuilder
from selenium.webdriver.common.actions.mouse_button import MouseButton
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
def test_click_and_hold ( driver ):
driver . get ( 'https://selenium.dev/selenium/web/mouse_interaction.html' )
clickable = driver . find_element ( By . ID , "clickable" )
ActionChains ( driver ) \
. click_and_hold ( clickable ) \
. perform ()
sleep ( 0.5 )
assert driver . find_element ( By . ID , "click-status" ) . text == "focused"
def test_click_and_release ( driver ):
driver . get ( 'https://selenium.dev/selenium/web/mouse_interaction.html' )
clickable = driver . find_element ( By . ID , "click" )
ActionChains ( driver ) \
. click ( clickable ) \
. perform ()
assert "resultPage.html" in driver . current_url
def test_right_click ( driver ):
driver . get ( 'https://selenium.dev/selenium/web/mouse_interaction.html' )
clickable = driver . find_element ( By . ID , "clickable" )
ActionChains ( driver ) \
. context_click ( clickable ) \
. perform ()
sleep ( 0.5 )
assert driver . find_element ( By . ID , "click-status" ) . text == "context-clicked"
def test_back_click_ab ( driver ):
driver . get ( 'https://selenium.dev/selenium/web/mouse_interaction.html' )
driver . find_element ( By . ID , "click" ) . click ()
assert driver . title == "We Arrive Here"
action = ActionBuilder ( driver )
action . pointer_action . pointer_down ( MouseButton . BACK )
action . pointer_action . pointer_up ( MouseButton . BACK )
action . perform ()
assert driver . title == "BasicMouseInterfaceTest"
def test_forward_click_ab ( driver ):
driver . get ( 'https://selenium.dev/selenium/web/mouse_interaction.html' )
driver . find_element ( By . ID , "click" ) . click ()
driver . back ()
assert driver . title == "BasicMouseInterfaceTest"
action = ActionBuilder ( driver )
action . pointer_action . pointer_down ( MouseButton . FORWARD )
action . pointer_action . pointer_up ( MouseButton . FORWARD )
action . perform ()
assert driver . title == "We Arrive Here"
def test_double_click ( driver ):
driver . get ( 'https://selenium.dev/selenium/web/mouse_interaction.html' )
clickable = driver . find_element ( By . ID , "clickable" )
ActionChains ( driver ) \
. double_click ( clickable ) \
. perform ()
assert driver . find_element ( By . ID , "click-status" ) . text == "double-clicked"
def test_hover ( driver ):
driver . get ( 'https://selenium.dev/selenium/web/mouse_interaction.html' )
hoverable = driver . find_element ( By . ID , "hover" )
ActionChains ( driver ) \
. move_to_element ( hoverable ) \
. perform ()
assert driver . find_element ( By . ID , "move-status" ) . text == "hovered"
def test_move_by_offset_from_element ( driver ):
driver . get ( 'https://selenium.dev/selenium/web/mouse_interaction.html' )
mouse_tracker = driver . find_element ( By . ID , "mouse-tracker" )
ActionChains ( driver ) \
. move_to_element_with_offset ( mouse_tracker , 8 , 0 ) \
. perform ()
coordinates = driver . find_element ( By . ID , "relative-location" ) . text . split ( ", " )
assert abs ( int ( coordinates [ 0 ]) - 100 - 8 ) < 2
def test_move_by_offset_from_viewport_origin_ab ( driver ):
driver . get ( 'https://selenium.dev/selenium/web/mouse_interaction.html' )
WebDriverWait ( driver , 10 ) . until ( EC . presence_of_element_located (( By . ID , "absolute-location" )))
action = ActionBuilder ( driver )
action . pointer_action . move_to_location ( 8 , 0 )
action . perform ()
coordinates = driver . find_element ( By . ID , "absolute-location" ) . text . split ( ", " )
assert abs ( int ( coordinates [ 0 ]) - 8 ) < 2
def test_move_by_offset_from_current_pointer_ab ( driver ):
driver . get ( 'https://selenium.dev/selenium/web/mouse_interaction.html' )
action = ActionBuilder ( driver )
action . pointer_action . move_to_location ( 6 , 3 )
action . perform ()
ActionChains ( driver ) \
. move_by_offset ( 13 , 15 ) \
. perform ()
coordinates = driver . find_element ( By . ID , "absolute-location" ) . text . split ( ", " )
assert abs ( int ( coordinates [ 0 ]) - 6 - 13 ) < 2
assert abs ( int ( coordinates [ 1 ]) - 3 - 15 ) < 2
def test_drag_and_drop_onto_element ( driver ):
driver . get ( 'https://selenium.dev/selenium/web/mouse_interaction.html' )
draggable = driver . find_element ( By . ID , "draggable" )
droppable = driver . find_element ( By . ID , "droppable" )
ActionChains ( driver ) \
. drag_and_drop ( draggable , droppable ) \
. perform ()
assert driver . find_element ( By . ID , "drop-status" ) . text == "dropped"
def test_drag_and_drop_by_offset ( driver ):
driver . get ( 'https://selenium.dev/selenium/web/mouse_interaction.html' )
draggable = driver . find_element ( By . ID , "draggable" )
start = draggable . location
finish = driver . find_element ( By . ID , "droppable" ) . location
ActionChains ( driver ) \
. drag_and_drop_by_offset ( draggable , finish [ 'x' ] - start [ 'x' ], finish [ 'y' ] - start [ 'y' ]) \
. perform ()
assert driver . find_element ( By . ID , "drop-status" ) . text == "dropped"
IWebElement draggable = driver . FindElement ( By . Id ( "draggable" ));
Point start = draggable . Location ;
Point finish = driver . FindElement ( By . Id ( "droppable" )). Location ;
new Actions ( driver )
. DragAndDropToOffset ( draggable , finish . X - start . X , finish . Y - start . Y )
. Perform ();
Show full example using System ;
using System.Drawing ;
using Microsoft.VisualStudio.TestTools.UnitTesting ;
using OpenQA.Selenium ;
using OpenQA.Selenium.Interactions ;
namespace SeleniumDocs.ActionsAPI
{
[TestClass]
public class MouseTest : BaseChromeTest
{
[TestMethod]
public void ClickAndHold ()
{
driver . Url = "https://selenium.dev/selenium/web/mouse_interaction.html" ;
IWebElement clickable = driver . FindElement ( By . Id ( "clickable" ));
new Actions ( driver )
. ClickAndHold ( clickable )
. Perform ();
Assert . AreEqual ( "focused" , driver . FindElement ( By . Id ( "click-status" )). Text );
}
[TestMethod]
public void ClickAndRelease ()
{
driver . Url = "https://selenium.dev/selenium/web/mouse_interaction.html" ;
IWebElement clickable = driver . FindElement ( By . Id ( "click" ));
new Actions ( driver )
. Click ( clickable )
. Perform ();
Assert . IsTrue ( driver . Url . Contains ( "resultPage.html" ));
}
[TestMethod]
public void RightClick ()
{
driver . Url = "https://selenium.dev/selenium/web/mouse_interaction.html" ;
IWebElement clickable = driver . FindElement ( By . Id ( "clickable" ));
new Actions ( driver )
. ContextClick ( clickable )
. Perform ();
Assert . AreEqual ( "context-clicked" , driver . FindElement ( By . Id ( "click-status" )). Text );
}
[TestMethod]
public void BackClick ()
{
driver . Url = "https://selenium.dev/selenium/web/mouse_interaction.html" ;
driver . FindElement ( By . Id ( "click" )). Click ();
Assert . AreEqual ( "We Arrive Here" , driver . Title );
ActionBuilder actionBuilder = new ActionBuilder ();
PointerInputDevice mouse = new PointerInputDevice ( PointerKind . Mouse , "default mouse" );
actionBuilder . AddAction ( mouse . CreatePointerDown ( MouseButton . Back ));
actionBuilder . AddAction ( mouse . CreatePointerUp ( MouseButton . Back ));
(( IActionExecutor ) driver ). PerformActions ( actionBuilder . ToActionSequenceList ());
Assert . AreEqual ( "BasicMouseInterfaceTest" , driver . Title );
}
[TestMethod]
public void ForwardClick ()
{
driver . Url = "https://selenium.dev/selenium/web/mouse_interaction.html" ;
driver . FindElement ( By . Id ( "click" )). Click ();
driver . Navigate (). Back ();
Assert . AreEqual ( "BasicMouseInterfaceTest" , driver . Title );
ActionBuilder actionBuilder = new ActionBuilder ();
PointerInputDevice mouse = new PointerInputDevice ( PointerKind . Mouse , "default mouse" );
actionBuilder . AddAction ( mouse . CreatePointerDown ( MouseButton . Forward ));
actionBuilder . AddAction ( mouse . CreatePointerUp ( MouseButton . Forward ));
(( IActionExecutor ) driver ). PerformActions ( actionBuilder . ToActionSequenceList ());
Assert . AreEqual ( "We Arrive Here" , driver . Title );
}
[TestMethod]
public void DoubleClick ()
{
driver . Url = "https://selenium.dev/selenium/web/mouse_interaction.html" ;
IWebElement clickable = driver . FindElement ( By . Id ( "clickable" ));
new Actions ( driver )
. DoubleClick ( clickable )
. Perform ();
Assert . AreEqual ( "double-clicked" , driver . FindElement ( By . Id ( "click-status" )). Text );
}
[TestMethod]
public void Hovers ()
{
driver . Url = "https://selenium.dev/selenium/web/mouse_interaction.html" ;
IWebElement hoverable = driver . FindElement ( By . Id ( "hover" ));
new Actions ( driver )
. MoveToElement ( hoverable )
. Perform ();
Assert . AreEqual ( "hovered" , driver . FindElement ( By . Id ( "move-status" )). Text );
}
[TestMethod]
[Obsolete("Obsolete")]
public void MoveByOffsetFromTopLeftOfElement ()
{
driver . Url = "https://selenium.dev/selenium/web/mouse_interaction.html" ;
IWebElement tracker = driver . FindElement ( By . Id ( "mouse-tracker" ));
new Actions ( driver )
. MoveToElement ( tracker , 8 , 0 )
. Perform ();
string [] result = driver . FindElement ( By . Id ( "relative-location" )). Text . Split ( ", " );
Assert . IsTrue ( Math . Abs ( int . Parse ( result [ 0 ]) - 100 - 8 ) < 2 );
}
[TestMethod]
public void MoveByOffsetFromCenterOfElement ()
{
driver . Url = "https://selenium.dev/selenium/web/mouse_interaction.html" ;
IWebElement tracker = driver . FindElement ( By . Id ( "mouse-tracker" ));
new Actions ( driver )
. MoveToElement ( tracker , 8 , 0 )
. Perform ();
string [] result = driver . FindElement ( By . Id ( "relative-location" )). Text . Split ( ", " );
Assert . IsTrue ( Math . Abs ( int . Parse ( result [ 0 ]) - 100 - 8 ) < 2 );
}
[TestMethod]
public void MoveByOffsetFromViewport ()
{
driver . Url = "https://selenium.dev/selenium/web/mouse_interaction.html" ;
ActionBuilder actionBuilder = new ActionBuilder ();
PointerInputDevice mouse = new PointerInputDevice ( PointerKind . Mouse , "default mouse" );
actionBuilder . AddAction ( mouse . CreatePointerMove ( CoordinateOrigin . Viewport ,
8 , 0 , TimeSpan . Zero ));
(( IActionExecutor ) driver ). PerformActions ( actionBuilder . ToActionSequenceList ());
string [] result = driver . FindElement ( By . Id ( "absolute-location" )). Text . Split ( ", " );
Assert . IsTrue ( Math . Abs ( int . Parse ( result [ 0 ]) - 8 ) < 2 );
}
[TestMethod]
public void MoveByOffsetFromCurrentPointerLocation ()
{
driver . Url = "https://selenium.dev/selenium/web/mouse_interaction.html" ;
ActionBuilder actionBuilder = new ActionBuilder ();
PointerInputDevice mouse = new PointerInputDevice ( PointerKind . Mouse , "default mouse" );
actionBuilder . AddAction ( mouse . CreatePointerMove ( CoordinateOrigin . Viewport ,
8 , 12 , TimeSpan . Zero ));
(( IActionExecutor ) driver ). PerformActions ( actionBuilder . ToActionSequenceList ());
new Actions ( driver )
. MoveByOffset ( 13 , 15 )
. Perform ();
string [] result = driver . FindElement ( By . Id ( "absolute-location" )). Text . Split ( ", " );
Assert . IsTrue ( Math . Abs ( int . Parse ( result [ 0 ]) - 8 - 13 ) < 2 );
Assert . IsTrue ( Math . Abs ( int . Parse ( result [ 1 ]) - 12 - 15 ) < 2 );
}
[TestMethod]
public void DragToElement ()
{
driver . Url = "https://selenium.dev/selenium/web/mouse_interaction.html" ;
IWebElement draggable = driver . FindElement ( By . Id ( "draggable" ));
IWebElement droppable = driver . FindElement ( By . Id ( "droppable" ));
new Actions ( driver )
. DragAndDrop ( draggable , droppable )
. Perform ();
Assert . AreEqual ( "dropped" , driver . FindElement ( By . Id ( "drop-status" )). Text );
}
[TestMethod]
public void DragByOffset ()
{
driver . Url = "https://selenium.dev/selenium/web/mouse_interaction.html" ;
IWebElement draggable = driver . FindElement ( By . Id ( "draggable" ));
Point start = draggable . Location ;
Point finish = driver . FindElement ( By . Id ( "droppable" )). Location ;
new Actions ( driver )
. DragAndDropToOffset ( draggable , finish . X - start . X , finish . Y - start . Y )
. Perform ();
Assert . AreEqual ( "dropped" , driver . FindElement ( By . Id ( "drop-status" )). Text );
}
}
}
draggable = driver . find_element ( id : 'draggable' )
start = draggable . rect
finish = driver . find_element ( id : 'droppable' ) . rect
driver . action
. drag_and_drop_by ( draggable , finish . x - start . x , finish . y - start . y )
. perform
Show full example # frozen_string_literal: true
require 'spec_helper'
RSpec . describe 'Mouse' do
let ( :driver ) { start_session }
it 'click and hold' do
driver . get 'https://www.selenium.dev/selenium/web/mouse_interaction.html'
clickable = driver . find_element ( id : 'clickable' )
driver . action
. click_and_hold ( clickable )
. perform
expect ( driver . find_element ( id : 'click-status' ) . text ) . to eq 'focused'
end
it 'click and release' do
driver . get 'https://www.selenium.dev/selenium/web/mouse_interaction.html'
clickable = driver . find_element ( id : 'click' )
driver . action
. click ( clickable )
. perform
expect ( driver . current_url ) . to include 'resultPage.html'
end
describe 'alternate button clicks' do
it 'right click' do
driver . get 'https://www.selenium.dev/selenium/web/mouse_interaction.html'
clickable = driver . find_element ( id : 'clickable' )
driver . action
. context_click ( clickable )
. perform
expect ( driver . find_element ( id : 'click-status' ) . text ) . to eq 'context-clicked'
end
it 'back click' do
driver . get 'https://www.selenium.dev/selenium/web/mouse_interaction.html'
driver . find_element ( id : 'click' ) . click
expect ( driver . title ) . to eq ( 'We Arrive Here' )
driver . action
. pointer_down ( :back )
. pointer_up ( :back )
. perform
expect ( driver . title ) . to eq ( 'BasicMouseInterfaceTest' )
end
it 'forward click' do
driver . get 'https://www.selenium.dev/selenium/web/mouse_interaction.html'
driver . find_element ( id : 'click' ) . click
driver . navigate . back
expect ( driver . title ) . to eq ( 'BasicMouseInterfaceTest' )
driver . action
. pointer_down ( :forward )
. pointer_up ( :forward )
. perform
expect ( driver . title ) . to eq ( 'We Arrive Here' )
end
end
it 'double click' do
driver . get 'https://www.selenium.dev/selenium/web/mouse_interaction.html'
clickable = driver . find_element ( id : 'clickable' )
driver . action
. double_click ( clickable )
. perform
expect ( driver . find_element ( id : 'click-status' ) . text ) . to eq 'double-clicked'
end
it 'hovers' do
driver . get 'https://www.selenium.dev/selenium/web/mouse_interaction.html'
hoverable = driver . find_element ( id : 'hover' )
driver . action
. move_to ( hoverable )
. perform
expect ( driver . find_element ( id : 'move-status' ) . text ) . to eq 'hovered'
end
describe 'move by offset' do
it 'offset from element' do
driver . get 'https://www.selenium.dev/selenium/web/mouse_interaction.html'
driver . action . scroll_to ( driver . find_element ( id : 'bottom' )) . perform
mouse_tracker = driver . find_element ( id : 'mouse-tracker' )
driver . action
. move_to ( mouse_tracker , 8 , 11 )
. perform
rect = mouse_tracker . rect
center_x = rect . width / 2
center_y = rect . height / 2
x_coord , y_coord = driver . find_element ( id : 'relative-location' ) . text . split ( ',' ) . map ( & :to_i )
expect ( x_coord ) . to be_within ( 1 ) . of ( center_x + 8 )
expect ( y_coord ) . to be_within ( 1 ) . of ( center_y + 11 )
end
it 'offset from viewport' do
driver . get 'https://www.selenium.dev/selenium/web/mouse_interaction.html'
driver . action
. move_to_location ( 8 , 12 )
. perform
x_coord , y_coord = driver . find_element ( id : 'absolute-location' ) . text . split ( ',' ) . map ( & :to_i )
expect ( x_coord ) . to be_within ( 1 ) . of ( 8 )
expect ( y_coord ) . to be_within ( 1 ) . of ( 12 )
end
it 'offset from current pointer location' do
driver . get 'https://www.selenium.dev/selenium/web/mouse_interaction.html'
driver . action . move_to_location ( 8 , 11 ) . perform
driver . action
. move_by ( 13 , 15 )
. perform
x_coord , y_coord = driver . find_element ( id : 'absolute-location' ) . text . split ( ',' ) . map ( & :to_i )
expect ( x_coord ) . to be_within ( 1 ) . of ( 8 + 13 )
expect ( y_coord ) . to be_within ( 1 ) . of ( 11 + 15 )
end
end
it 'drags to another element' do
driver . get 'https://www.selenium.dev/selenium/web/mouse_interaction.html'
draggable = driver . find_element ( id : 'draggable' )
droppable = driver . find_element ( id : 'droppable' )
driver . action
. drag_and_drop ( draggable , droppable )
. perform
expect ( driver . find_element ( id : 'drop-status' ) . text ) . to include ( 'dropped' )
end
it 'drags by an offset' do
driver . get 'https://www.selenium.dev/selenium/web/mouse_interaction.html'
draggable = driver . find_element ( id : 'draggable' )
start = draggable . rect
finish = driver . find_element ( id : 'droppable' ) . rect
driver . action
. drag_and_drop_by ( draggable , finish . x - start . x , finish . y - start . y )
. perform
expect ( driver . find_element ( id : 'drop-status' ) . text ) . to include ( 'dropped' )
end
end
const draggable = driver . findElement ( By . id ( "draggable" ));
let start = await draggable . getRect ();
let finish = await driver . findElement ( By . id ( "droppable" )). getRect ();
const actions = driver . actions ({ async : true });
await actions . dragAndDrop ( draggable , { x : finish . x - start . x , y : finish . y - start . y }). perform ();
Show full example const { By , Builder } = require ( 'selenium-webdriver' );
const assert = require ( 'assert' );
describe ( 'Drag and Drop' , function () {
let driver ;
before ( async function () {
driver = new Builder (). forBrowser ( 'chrome' ). build ();
});
after ( async () => await driver . quit ());
it ( 'By Offset' , async function () {
await driver . get ( 'https://www.selenium.dev/selenium/web/mouse_interaction.html' );
const draggable = driver . findElement ( By . id ( "draggable" ));
let start = await draggable . getRect ();
let finish = await driver . findElement ( By . id ( "droppable" )). getRect ();
const actions = driver . actions ({ async : true });
await actions . dragAndDrop ( draggable , { x : finish . x - start . x , y : finish . y - start . y }). perform ();
let result = await driver . findElement ( By . id ( "drop-status" )). getText ();
assert . deepStrictEqual ( 'dropped' , result )
});
it ( 'Onto Element' , async function () {
await driver . get ( 'https://www.selenium.dev/selenium/web/mouse_interaction.html' );
const draggable = driver . findElement ( By . id ( "draggable" ));
const droppable = await driver . findElement ( By . id ( "droppable" ));
const actions = driver . actions ({ async : true });
await actions . dragAndDrop ( draggable , droppable ). perform ();
let result = await driver . findElement ( By . id ( "drop-status" )). getText ();
assert . deepStrictEqual ( 'dropped' , result )
});
});
val draggable = driver . findElement ( By . id ( "draggable" ))
val start = draggable . getRect ()
val finish = driver . findElement ( By . id ( "droppable" )). getRect ()
Actions ( driver )
. dragAndDropBy ( draggable , finish . getX () - start . getX (), finish . getY () - start . getY ())
. perform ()
Show full example 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.Rectangle
import org.openqa.selenium.WebElement
import org.openqa.selenium.interactions.Actions
import org.openqa.selenium.interactions.PointerInput
import org.openqa.selenium.interactions.Sequence
import org.openqa.selenium.remote.RemoteWebDriver
import java.time.Duration
import java.util.Collections
class MouseTest : BaseTest () {
@Test
fun clickAndHold () {
driver . get ( "https://www.selenium.dev/selenium/web/mouse_interaction.html" )
val clickable = driver . findElement ( By . id ( "clickable" ))
Actions ( driver )
. clickAndHold ( clickable )
. perform ()
Assertions . assertEquals ( "focused" , driver . findElement ( By . id ( "click-status" )). getText ())
}
@Test
fun clickAndRelease () {
driver . get ( "https://www.selenium.dev/selenium/web/mouse_interaction.html" )
val clickable = driver . findElement ( By . id ( "click" ))
Actions ( driver )
. click ( clickable )
. perform ()
Assertions . assertTrue ( driver . getCurrentUrl () !! . contains ( "resultPage.html" ))
}
@Test
fun rightClick () {
driver . get ( "https://www.selenium.dev/selenium/web/mouse_interaction.html" )
val clickable = driver . findElement ( By . id ( "clickable" ))
Actions ( driver )
. contextClick ( clickable )
. perform ()
Assertions . assertEquals ( "context-clicked" , driver . findElement ( By . id ( "click-status" )). getText ())
}
@Test
fun backClick () {
driver . get ( "https://www.selenium.dev/selenium/web/mouse_interaction.html" )
driver . findElement ( By . id ( "click" )). click ()
Assertions . assertEquals ( driver . getTitle (), "We Arrive Here" )
val mouse = PointerInput ( PointerInput . Kind . MOUSE , "default mouse" )
val actions = Sequence ( mouse , 0 )
. addAction ( mouse . createPointerDown ( PointerInput . MouseButton . BACK . asArg ()))
. addAction ( mouse . createPointerUp ( PointerInput . MouseButton . BACK . asArg ()))
( driver as RemoteWebDriver ). perform ( Collections . singletonList ( actions ))
Assertions . assertEquals ( "BasicMouseInterfaceTest" , driver . getTitle ())
}
@Test
fun forwardClick () {
driver . get ( "https://www.selenium.dev/selenium/web/mouse_interaction.html" )
driver . findElement ( By . id ( "click" )). click ()
driver . navigate (). back ()
Assertions . assertEquals ( driver . getTitle (), "BasicMouseInterfaceTest" )
val mouse = PointerInput ( PointerInput . Kind . MOUSE , "default mouse" )
val actions = Sequence ( mouse , 0 )
. addAction ( mouse . createPointerDown ( PointerInput . MouseButton . FORWARD . asArg ()))
. addAction ( mouse . createPointerUp ( PointerInput . MouseButton . FORWARD . asArg ()))
( driver as RemoteWebDriver ). perform ( Collections . singletonList ( actions ))
Assertions . assertEquals ( "We Arrive Here" , driver . getTitle ())
}
@Test
fun doubleClick () {
driver . get ( "https://www.selenium.dev/selenium/web/mouse_interaction.html" )
val clickable = driver . findElement ( By . id ( "clickable" ))
Actions ( driver )
. doubleClick ( clickable )
. perform ()
Assertions . assertEquals ( "double-clicked" , driver . findElement ( By . id ( "click-status" )). getText ())
}
@Test
fun hovers () {
driver . get ( "https://www.selenium.dev/selenium/web/mouse_interaction.html" )
val hoverable = driver . findElement ( By . id ( "hover" ))
Actions ( driver )
. moveToElement ( hoverable )
. perform ()
Assertions . assertEquals ( "hovered" , driver . findElement ( By . id ( "move-status" )). getText ())
}
@Test
fun moveByOffsetFromElement () {
driver . get ( "https://www.selenium.dev/selenium/web/mouse_interaction.html" )
driver . manage (). window (). fullscreen ()
val tracker = driver . findElement ( By . id ( "mouse-tracker" ))
Actions ( driver )
. moveToElement ( tracker , 8 , 0 )
. perform ()
val result = driver . findElement ( By . id ( "relative-location" )). getText (). split ( ", " )
Assertions . assertTrue ( Math . abs ( Integer . parseInt ( result [ 0 ]) - 100 - 8 ) < 2 )
}
@Test
fun moveByOffsetFromViewport () {
driver . get ( "https://www.selenium.dev/selenium/web/mouse_interaction.html" )
val mouse = PointerInput ( PointerInput . Kind . MOUSE , "default mouse" )
val actions = Sequence ( mouse , 0 )
. addAction ( mouse . createPointerMove ( Duration . ZERO , PointerInput . Origin . viewport (), 8 , 12 ))
( driver as RemoteWebDriver ). perform ( Collections . singletonList ( actions ))
val result = driver . findElement ( By . id ( "absolute-location" )). getText (). split ( ", " )
Assertions . assertTrue ( Math . abs ( Integer . parseInt ( result [ 0 ]) - 8 ) < 2 )
Assertions . assertTrue ( Math . abs ( Integer . parseInt ( result [ 1 ]) - 12 ) < 2 )
}
@Test
fun moveByOffsetFromCurrentPointer () {
driver . get ( "https://www.selenium.dev/selenium/web/mouse_interaction.html" )
val mouse = PointerInput ( PointerInput . Kind . MOUSE , "default mouse" )
val actions = Sequence ( mouse , 0 )
. addAction ( mouse . createPointerMove ( Duration . ZERO , PointerInput . Origin . viewport (), 8 , 11 ))
( driver as RemoteWebDriver ). perform ( Collections . singletonList ( actions ))
Actions ( driver )
. moveByOffset ( 13 , 15 )
. perform ()
val result = driver . findElement ( By . id ( "absolute-location" )). getText (). split ( ", " )
Assertions . assertTrue ( Math . abs ( Integer . parseInt ( result [ 0 ]) - 8 - 13 ) < 2 )
Assertions . assertTrue ( Math . abs ( Integer . parseInt ( result [ 1 ]) - 11 - 15 ) < 2 )
}
@Test
fun dragsToElement () {
driver . get ( "https://www.selenium.dev/selenium/web/mouse_interaction.html" )
val draggable = driver . findElement ( By . id ( "draggable" ))
val droppable = driver . findElement ( By . id ( "droppable" ))
Actions ( driver )
. dragAndDrop ( draggable , droppable )
. perform ()
Assertions . assertEquals ( "dropped" , driver . findElement ( By . id ( "drop-status" )). getText ())
}
@Test
fun dragsByOffset () {
driver . get ( "https://www.selenium.dev/selenium/web/mouse_interaction.html" )
val draggable = driver . findElement ( By . id ( "draggable" ))
val start = draggable . getRect ()
val finish = driver . findElement ( By . id ( "droppable" )). getRect ()
Actions ( driver )
. dragAndDropBy ( draggable , finish . getX () - start . getX (), finish . getY () - start . getY ())
. perform ()
Assertions . assertEquals ( "dropped" , driver . findElement ( By . id ( "drop-status" )). getText ())
}
}
3 - Ações de Caneta Uma representação de uma entrada de ponteiro do tipo caneta stylus para interagir com uma página da web.
Chromium Only
Uma caneta é um tipo de entrada de ponteiro que possui a maior parte do mesmo comportamento que um mouse, mas também pode ter propriedades de evento únicas para uma caneta stylus. Além disso, enquanto um mouse possui 5 botões, uma caneta possui 3 estados equivalentes de botão:
0 — Contato por Toque (o padrão; equivalente a um clique com o botão esquerdo) 2 — Botão do Barril (equivalente a um clique com o botão direito) 5 — Botão de Borracha (atualmente não suportado pelos drivers) Usando uma Caneta
Java
Python
CSharp
Ruby
JavaScript
Kotlin Selenium v4.2
WebElement pointerArea = driver . findElement ( By . id ( "pointerArea" ));
new Actions ( driver )
. setActivePointer ( PointerInput . Kind . PEN , "default pen" )
. moveToElement ( pointerArea )
. clickAndHold ()
. moveByOffset ( 2 , 2 )
. release ()
. perform ();
Show full example 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.Rectangle ;
import org.openqa.selenium.WebElement ;
import org.openqa.selenium.interactions.Actions ;
import org.openqa.selenium.interactions.PointerInput ;
import org.openqa.selenium.interactions.Sequence ;
import org.openqa.selenium.remote.RemoteWebDriver ;
import java.time.Duration ;
import java.util.Arrays ;
import java.util.Collections ;
import java.util.List ;
import java.util.Map ;
import java.util.stream.Collectors ;
public class PenTest extends BaseChromeTest {
@Test
public void usePen () {
driver . get ( "https://www.selenium.dev/selenium/web/pointerActionsPage.html" );
WebElement pointerArea = driver . findElement ( By . id ( "pointerArea" ));
new Actions ( driver )
. setActivePointer ( PointerInput . Kind . PEN , "default pen" )
. moveToElement ( pointerArea )
. clickAndHold ()
. moveByOffset ( 2 , 2 )
. release ()
. perform ();
List < WebElement > moves = driver . findElements ( By . className ( "pointermove" ));
Map < String , String > moveTo = getPropertyInfo ( moves . get ( 0 ));
Map < String , String > down = getPropertyInfo ( driver . findElement ( By . className ( "pointerdown" )));
Map < String , String > moveBy = getPropertyInfo ( moves . get ( 1 ));
Map < String , String > up = getPropertyInfo ( driver . findElement ( By . className ( "pointerup" )));
Rectangle rect = pointerArea . getRect ();
int centerX = ( int ) Math . floor ( rect . width / 2 + rect . getX ());
int centerY = ( int ) Math . floor ( rect . height / 2 + rect . getY ());
Assertions . assertEquals ( "-1" , moveTo . get ( "button" ));
Assertions . assertEquals ( "pen" , moveTo . get ( "pointerType" ));
Assertions . assertEquals ( String . valueOf ( centerX ), moveTo . get ( "pageX" ));
Assertions . assertEquals ( String . valueOf ( centerY ), moveTo . get ( "pageY" ));
Assertions . assertEquals ( "0" , down . get ( "button" ));
Assertions . assertEquals ( "pen" , down . get ( "pointerType" ));
Assertions . assertEquals ( String . valueOf ( centerX ), down . get ( "pageX" ));
Assertions . assertEquals ( String . valueOf ( centerY ), down . get ( "pageY" ));
Assertions . assertEquals ( "-1" , moveBy . get ( "button" ));
Assertions . assertEquals ( "pen" , moveBy . get ( "pointerType" ));
Assertions . assertEquals ( String . valueOf ( centerX + 2 ), moveBy . get ( "pageX" ));
Assertions . assertEquals ( String . valueOf ( centerY + 2 ), moveBy . get ( "pageY" ));
Assertions . assertEquals ( "0" , up . get ( "button" ));
Assertions . assertEquals ( "pen" , up . get ( "pointerType" ));
Assertions . assertEquals ( String . valueOf ( centerX + 2 ), up . get ( "pageX" ));
Assertions . assertEquals ( String . valueOf ( centerY + 2 ), up . get ( "pageY" ));
}
@Test
public void setPointerEventProperties () {
driver . get ( "https://selenium.dev/selenium/web/pointerActionsPage.html" );
WebElement pointerArea = driver . findElement ( By . id ( "pointerArea" ));
PointerInput pen = new PointerInput ( PointerInput . Kind . PEN , "default pen" );
PointerInput . PointerEventProperties eventProperties = PointerInput . eventProperties ()
. setTiltX ( - 72 )
. setTiltY ( 9 )
. setTwist ( 86 );
PointerInput . Origin origin = PointerInput . Origin . fromElement ( pointerArea );
Sequence actionListPen = new Sequence ( pen , 0 )
. addAction ( pen . createPointerMove ( Duration . ZERO , origin , 0 , 0 ))
. addAction ( pen . createPointerDown ( 0 ))
. addAction ( pen . createPointerMove ( Duration . ZERO , origin , 2 , 2 , eventProperties ))
. addAction ( pen . createPointerUp ( 0 ));
(( RemoteWebDriver ) driver ). perform ( Collections . singletonList ( actionListPen ));
List < WebElement > moves = driver . findElements ( By . className ( "pointermove" ));
Map < String , String > moveTo = getPropertyInfo ( moves . get ( 0 ));
Map < String , String > down = getPropertyInfo ( driver . findElement ( By . className ( "pointerdown" )));
Map < String , String > moveBy = getPropertyInfo ( moves . get ( 1 ));
Map < String , String > up = getPropertyInfo ( driver . findElement ( By . className ( "pointerup" )));
Rectangle rect = pointerArea . getRect ();
int centerX = ( int ) Math . floor ( rect . width / 2 + rect . getX ());
int centerY = ( int ) Math . floor ( rect . height / 2 + rect . getY ());
Assertions . assertEquals ( "-1" , moveTo . get ( "button" ));
Assertions . assertEquals ( "pen" , moveTo . get ( "pointerType" ));
Assertions . assertEquals ( String . valueOf ( centerX ), moveTo . get ( "pageX" ));
Assertions . assertEquals ( String . valueOf ( centerY ), moveTo . get ( "pageY" ));
Assertions . assertEquals ( "0" , down . get ( "button" ));
Assertions . assertEquals ( "pen" , down . get ( "pointerType" ));
Assertions . assertEquals ( String . valueOf ( centerX ), down . get ( "pageX" ));
Assertions . assertEquals ( String . valueOf ( centerY ), down . get ( "pageY" ));
Assertions . assertEquals ( "-1" , moveBy . get ( "button" ));
Assertions . assertEquals ( "pen" , moveBy . get ( "pointerType" ));
Assertions . assertEquals ( String . valueOf ( centerX + 2 ), moveBy . get ( "pageX" ));
Assertions . assertEquals ( String . valueOf ( centerY + 2 ), moveBy . get ( "pageY" ));
Assertions . assertEquals ( "-72" , moveBy . get ( "tiltX" ));
Assertions . assertEquals ( "9" , moveBy . get ( "tiltY" ));
Assertions . assertEquals ( "86" , moveBy . get ( "twist" ));
Assertions . assertEquals ( "0" , up . get ( "button" ));
Assertions . assertEquals ( "pen" , up . get ( "pointerType" ));
Assertions . assertEquals ( String . valueOf ( centerX + 2 ), up . get ( "pageX" ));
Assertions . assertEquals ( String . valueOf ( centerY + 2 ), up . get ( "pageY" ));
}
private Map < String , String > getPropertyInfo ( WebElement element ) {
String text = element . getText ();
text = text . substring ( text . indexOf ( ' ' ) + 1 );
return Arrays . stream ( text . split ( ", " ))
. map ( s -> s . split ( ": " ))
. collect ( Collectors . toMap (
a -> a [ 0 ] ,
a -> a [ 1 ]
));
}
}
Selenium v4.2
pointer_area = driver . find_element ( By . ID , "pointerArea" )
pen_input = PointerInput ( POINTER_PEN , "default pen" )
action = ActionBuilder ( driver , mouse = pen_input )
action . pointer_action \
. move_to ( pointer_area ) \
. pointer_down () \
. move_by ( 2 , 2 ) \
. pointer_up ()
action . perform ()
Show full example import math
from selenium.webdriver.common.actions.action_builder import ActionBuilder
from selenium.webdriver.common.actions.interaction import POINTER_PEN
from selenium.webdriver.common.actions.pointer_input import PointerInput
from selenium.webdriver.common.by import By
def test_use_pen ( driver ):
driver . get ( 'https://www.selenium.dev/selenium/web/pointerActionsPage.html' )
pointer_area = driver . find_element ( By . ID , "pointerArea" )
pen_input = PointerInput ( POINTER_PEN , "default pen" )
action = ActionBuilder ( driver , mouse = pen_input )
action . pointer_action \
. move_to ( pointer_area ) \
. pointer_down () \
. move_by ( 2 , 2 ) \
. pointer_up ()
action . perform ()
moves = driver . find_elements ( By . CLASS_NAME , "pointermove" )
move_to = properties ( moves [ 0 ])
down = properties ( driver . find_element ( By . CLASS_NAME , "pointerdown" ))
move_by = properties ( moves [ 1 ])
up = properties ( driver . find_element ( By . CLASS_NAME , "pointerup" ))
rect = pointer_area . rect
center_x = rect [ "x" ] + rect [ "width" ] / 2
center_y = rect [ "y" ] + rect [ "height" ] / 2
assert move_to [ "button" ] == "-1"
assert move_to [ "pointerType" ] == "pen"
assert move_to [ "pageX" ] == str ( math . floor ( center_x ))
assert move_to [ "pageY" ] == str ( math . floor ( center_y ))
assert down [ "button" ] == "0"
assert down [ "pointerType" ] == "pen"
assert down [ "pageX" ] == str ( math . floor ( center_x ))
assert down [ "pageY" ] == str ( math . floor ( center_y ))
assert move_by [ "button" ] == "-1"
assert move_by [ "pointerType" ] == "pen"
assert move_by [ "pageX" ] == str ( math . floor ( center_x + 2 ))
assert move_by [ "pageY" ] == str ( math . floor ( center_y + 2 ))
assert up [ "button" ] == "0"
assert up [ "pointerType" ] == "pen"
assert up [ "pageX" ] == str ( math . floor ( center_x + 2 ))
assert up [ "pageY" ] == str ( math . floor ( center_y + 2 ))
def test_set_pointer_event_properties ( driver ):
driver . get ( 'https://www.selenium.dev/selenium/web/pointerActionsPage.html' )
pointer_area = driver . find_element ( By . ID , "pointerArea" )
pen_input = PointerInput ( POINTER_PEN , "default pen" )
action = ActionBuilder ( driver , mouse = pen_input )
action . pointer_action \
. move_to ( pointer_area ) \
. pointer_down () \
. move_by ( 2 , 2 , tilt_x =- 72 , tilt_y = 9 , twist = 86 ) \
. pointer_up ( 0 )
action . perform ()
moves = driver . find_elements ( By . CLASS_NAME , "pointermove" )
move_to = properties ( moves [ 0 ])
down = properties ( driver . find_element ( By . CLASS_NAME , "pointerdown" ))
move_by = properties ( moves [ 1 ])
up = properties ( driver . find_element ( By . CLASS_NAME , "pointerup" ))
rect = pointer_area . rect
center_x = rect [ "x" ] + rect [ "width" ] / 2
center_y = rect [ "y" ] + rect [ "height" ] / 2
assert move_to [ "button" ] == "-1"
assert move_to [ "pointerType" ] == "pen"
assert move_to [ "pageX" ] == str ( math . floor ( center_x ))
assert move_to [ "pageY" ] == str ( math . floor ( center_y ))
assert down [ "button" ] == "0"
assert down [ "pointerType" ] == "pen"
assert down [ "pageX" ] == str ( math . floor ( center_x ))
assert down [ "pageY" ] == str ( math . floor ( center_y ))
assert move_by [ "button" ] == "-1"
assert move_by [ "pointerType" ] == "pen"
assert move_by [ "pageX" ] == str ( math . floor ( center_x + 2 ))
assert move_by [ "pageY" ] == str ( math . floor ( center_y + 2 ))
assert move_by [ "tiltX" ] == "-72"
assert move_by [ "tiltY" ] == "9"
assert move_by [ "twist" ] == "86"
assert up [ "button" ] == "0"
assert up [ "pointerType" ] == "pen"
assert up [ "pageX" ] == str ( math . floor ( center_x + 2 ))
assert up [ "pageY" ] == str ( math . floor ( center_y + 2 ))
def properties ( element ):
kv = element . text . split ( ' ' , 1 )[ 1 ] . split ( ', ' )
return { x [ 0 ]: x [ 1 ] for x in list ( map ( lambda item : item . split ( ': ' ), kv ))}
IWebElement pointerArea = driver . FindElement ( By . Id ( "pointerArea" ));
ActionBuilder actionBuilder = new ActionBuilder ();
PointerInputDevice pen = new PointerInputDevice ( PointerKind . Pen , "default pen" );
actionBuilder . AddAction ( pen . CreatePointerMove ( pointerArea , 0 , 0 , TimeSpan . FromMilliseconds ( 800 )));
actionBuilder . AddAction ( pen . CreatePointerDown ( MouseButton . Left ));
actionBuilder . AddAction ( pen . CreatePointerMove ( CoordinateOrigin . Pointer ,
2 , 2 , TimeSpan . Zero ));
actionBuilder . AddAction ( pen . CreatePointerUp ( MouseButton . Left ));
(( IActionExecutor ) driver ). PerformActions ( actionBuilder . ToActionSequenceList ());
Show full example using System ;
using System.Collections.Generic ;
using System.Drawing ;
using System.Linq ;
using Microsoft.VisualStudio.TestTools.UnitTesting ;
using OpenQA.Selenium ;
using OpenQA.Selenium.Interactions ;
namespace SeleniumDocs.ActionsAPI
{
[TestClass]
public class PenTest : BaseChromeTest
{
[TestMethod]
public void UsePen ()
{
driver . Url = "https://selenium.dev/selenium/web/pointerActionsPage.html" ;
IWebElement pointerArea = driver . FindElement ( By . Id ( "pointerArea" ));
ActionBuilder actionBuilder = new ActionBuilder ();
PointerInputDevice pen = new PointerInputDevice ( PointerKind . Pen , "default pen" );
actionBuilder . AddAction ( pen . CreatePointerMove ( pointerArea , 0 , 0 , TimeSpan . FromMilliseconds ( 800 )));
actionBuilder . AddAction ( pen . CreatePointerDown ( MouseButton . Left ));
actionBuilder . AddAction ( pen . CreatePointerMove ( CoordinateOrigin . Pointer ,
2 , 2 , TimeSpan . Zero ));
actionBuilder . AddAction ( pen . CreatePointerUp ( MouseButton . Left ));
(( IActionExecutor ) driver ). PerformActions ( actionBuilder . ToActionSequenceList ());
var moves = driver . FindElements ( By . ClassName ( "pointermove" ));
var moveTo = getProperties ( moves . ElementAt ( 0 ));
var down = getProperties ( driver . FindElement ( By . ClassName ( "pointerdown" )));
var moveBy = getProperties ( moves . ElementAt ( 1 ));
var up = getProperties ( driver . FindElement ( By . ClassName ( "pointerup" )));
Point location = pointerArea . Location ;
Size size = pointerArea . Size ;
decimal centerX = location . X + size . Width / 2 ;
decimal centerY = location . Y + size . Height / 2 ;
Assert . AreEqual ( "-1" , moveTo [ "button" ]);
Assert . AreEqual ( "pen" , moveTo [ "pointerType" ]);
Assert . IsTrue ( VerifyEquivalent ( centerX , moveTo [ "pageX" ]));
Assert . IsTrue ( VerifyEquivalent ( centerY , moveTo [ "pageY" ]));
Assert . AreEqual ( "0" , down [ "button" ]);
Assert . AreEqual ( "pen" , down [ "pointerType" ]);
Assert . IsTrue ( VerifyEquivalent ( centerX , down [ "pageX" ]));
Assert . IsTrue ( VerifyEquivalent ( centerY , down [ "pageY" ]));
Assert . AreEqual ( "-1" , moveBy [ "button" ]);
Assert . AreEqual ( "pen" , moveBy [ "pointerType" ]);
Assert . IsTrue ( VerifyEquivalent ( centerX + 2 , moveBy [ "pageX" ]));
Assert . IsTrue ( VerifyEquivalent ( centerY + 2 , moveBy [ "pageY" ]));
Assert . AreEqual ( "0" , up [ "button" ]);
Assert . AreEqual ( "pen" , up [ "pointerType" ]);
Assert . IsTrue ( VerifyEquivalent ( centerX + 2 , up [ "pageX" ]));
Assert . IsTrue ( VerifyEquivalent ( centerY + 2 , up [ "pageY" ]));
}
[TestMethod]
public void SetPointerEventProperties ()
{
driver . Url = "https://selenium.dev/selenium/web/pointerActionsPage.html" ;
IWebElement pointerArea = driver . FindElement ( By . Id ( "pointerArea" ));
ActionBuilder actionBuilder = new ActionBuilder ();
PointerInputDevice pen = new PointerInputDevice ( PointerKind . Pen , "default pen" );
PointerInputDevice . PointerEventProperties properties = new PointerInputDevice . PointerEventProperties () {
TiltX = - 72 ,
TiltY = 9 ,
Twist = 86 ,
};
actionBuilder . AddAction ( pen . CreatePointerMove ( pointerArea , 0 , 0 , TimeSpan . FromMilliseconds ( 800 )));
actionBuilder . AddAction ( pen . CreatePointerDown ( MouseButton . Left ));
actionBuilder . AddAction ( pen . CreatePointerMove ( CoordinateOrigin . Pointer ,
2 , 2 , TimeSpan . Zero , properties ));
actionBuilder . AddAction ( pen . CreatePointerUp ( MouseButton . Left ));
(( IActionExecutor ) driver ). PerformActions ( actionBuilder . ToActionSequenceList ());
var moves = driver . FindElements ( By . ClassName ( "pointermove" ));
var moveTo = getProperties ( moves . ElementAt ( 0 ));
var down = getProperties ( driver . FindElement ( By . ClassName ( "pointerdown" )));
var moveBy = getProperties ( moves . ElementAt ( 1 ));
var up = getProperties ( driver . FindElement ( By . ClassName ( "pointerup" )));
Point location = pointerArea . Location ;
Size size = pointerArea . Size ;
decimal centerX = location . X + size . Width / 2 ;
decimal centerY = location . Y + size . Height / 2 ;
Assert . AreEqual ( "-1" , moveTo [ "button" ]);
Assert . AreEqual ( "pen" , moveTo [ "pointerType" ]);
Assert . IsTrue ( VerifyEquivalent ( centerX , moveTo [ "pageX" ]));
Assert . IsTrue ( VerifyEquivalent ( centerY , moveTo [ "pageY" ]));
Assert . AreEqual ( "0" , down [ "button" ]);
Assert . AreEqual ( "pen" , down [ "pointerType" ]);
Assert . IsTrue ( VerifyEquivalent ( centerX , down [ "pageX" ]));
Assert . IsTrue ( VerifyEquivalent ( centerY , down [ "pageY" ]));
Assert . AreEqual ( "-1" , moveBy [ "button" ]);
Assert . AreEqual ( "pen" , moveBy [ "pointerType" ]);
Assert . IsTrue ( VerifyEquivalent ( centerX + 2 , moveBy [ "pageX" ]));
Assert . IsTrue ( VerifyEquivalent ( centerY + 2 , moveBy [ "pageY" ]));
Assert . AreEqual ((- 72 ). ToString (), moveBy [ "tiltX" ]);
Assert . AreEqual (( 9 ). ToString (), moveBy [ "tiltY" ]);
Assert . AreEqual (( 86 ). ToString (), moveBy [ "twist" ]);
Assert . AreEqual ( "0" , up [ "button" ]);
Assert . AreEqual ( "pen" , up [ "pointerType" ]);
Assert . IsTrue ( VerifyEquivalent ( centerX + 2 , up [ "pageX" ]));
Assert . IsTrue ( VerifyEquivalent ( centerY + 2 , up [ "pageY" ]));
}
private Dictionary < string , string > getProperties ( IWebElement element )
{
var str = element . Text ;
str = str [( str . Split ()[ 0 ]. Length + 1 )..];
IEnumerable < string []> keyValue = str . Split ( ", " ). Select ( part => part . Split ( ":" ));
return keyValue . ToDictionary ( split => split [ 0 ]. Trim (), split => split [ 1 ]. Trim ());
}
private bool VerifyEquivalent ( decimal expected , string actual )
{
var absolute = Math . Abs ( expected - decimal . Parse ( actual ));
if ( absolute <= 1 )
{
return true ;
}
throw new Exception ( "Expected: " + expected + "; but received: " + actual );
}
}
}
Selenium v4.2
pointer_area = driver . find_element ( id : 'pointerArea' )
driver . action ( devices : :pen )
. move_to ( pointer_area )
. pointer_down
. move_by ( 2 , 2 )
. pointer_up
. perform
Show full example # frozen_string_literal: true
require 'spec_helper'
RSpec . describe 'Pen' do
let ( :driver ) { start_session }
it 'uses a pen' do
driver . get 'https://www.selenium.dev/selenium/web/pointerActionsPage.html'
pointer_area = driver . find_element ( id : 'pointerArea' )
driver . action ( devices : :pen )
. move_to ( pointer_area )
. pointer_down
. move_by ( 2 , 2 )
. pointer_up
. perform
moves = driver . find_elements ( class : 'pointermove' )
move_to = properties ( moves [ 0 ] )
down = properties ( driver . find_element ( class : 'pointerdown' ))
move_by = properties ( moves [ 1 ] )
up = properties ( driver . find_element ( class : 'pointerup' ))
rect = pointer_area . rect
center_x = rect . x + ( rect . width / 2 )
center_y = rect . y + ( rect . height / 2 )
expect ( move_to ) . to include ( 'button' => '-1' ,
'pointerType' => 'pen' ,
'pageX' => center_x . to_s ,
'pageY' => center_y . floor . to_s )
expect ( down ) . to include ( 'button' => '0' ,
'pointerType' => 'pen' ,
'pageX' => center_x . to_s ,
'pageY' => center_y . floor . to_s )
expect ( move_by ) . to include ( 'button' => '-1' ,
'pointerType' => 'pen' ,
'pageX' => ( center_x + 2 ) . to_s ,
'pageY' => ( center_y + 2 ) . floor . to_s )
expect ( up ) . to include ( 'button' => '0' ,
'pointerType' => 'pen' ,
'pageX' => ( center_x + 2 ) . to_s ,
'pageY' => ( center_y + 2 ) . floor . to_s )
end
it 'sets pointer event attributes' do
driver . get 'https://www.selenium.dev/selenium/web/pointerActionsPage.html'
pointer_area = driver . find_element ( id : 'pointerArea' )
driver . action ( devices : :pen )
. move_to ( pointer_area )
. pointer_down
. move_by ( 2 , 2 , tilt_x : - 72 , tilt_y : 9 , twist : 86 )
. pointer_up
. perform
moves = driver . find_elements ( class : 'pointermove' )
move_to = properties ( moves [ 0 ] )
down = properties ( driver . find_element ( class : 'pointerdown' ))
move_by = properties ( moves [ 1 ] )
up = properties ( driver . find_element ( class : 'pointerup' ))
rect = pointer_area . rect
center_x = rect . x + ( rect . width / 2 )
center_y = rect . y + ( rect . height / 2 )
expect ( move_to ) . to include ( 'button' => '-1' ,
'pointerType' => 'pen' ,
'pageX' => center_x . to_s ,
'pageY' => center_y . floor . to_s )
expect ( down ) . to include ( 'button' => '0' ,
'pointerType' => 'pen' ,
'pageX' => center_x . to_s ,
'pageY' => center_y . floor . to_s )
expect ( move_by ) . to include ( 'button' => '-1' ,
'pointerType' => 'pen' ,
'pageX' => ( center_x + 2 ) . to_s ,
'pageY' => ( center_y + 2 ) . floor . to_s ,
'tiltX' => - 72 . to_s ,
'tiltY' => 9 . to_s ,
'twist' => 86 . to_s )
expect ( up ) . to include ( 'button' => '0' ,
'pointerType' => 'pen' ,
'pageX' => ( center_x + 2 ) . to_s ,
'pageY' => ( center_y + 2 ) . floor . to_s )
end
def properties ( element )
element . text . sub ( /.*?\s/ , '' ) . split ( ',' ) . to_h { | item | item . lstrip . split ( /\s*:\s*/ ) }
end
end
val pointerArea = driver . findElement ( By . id ( "pointerArea" ))
Actions ( driver )
. setActivePointer ( PointerInput . Kind . PEN , "default pen" )
. moveToElement ( pointerArea )
. clickAndHold ()
. moveByOffset ( 2 , 2 )
. release ()
. perform ()
Show full example 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.Rectangle
import org.openqa.selenium.WebElement
import org.openqa.selenium.interactions.Actions
import org.openqa.selenium.interactions.PointerInput
import org.openqa.selenium.interactions.Sequence
import org.openqa.selenium.remote.RemoteWebDriver
import kotlin.collections.Map
import java.time.Duration
class PenTest : BaseTest () {
@Test
fun usePen () {
driver . get ( "https://www.selenium.dev/selenium/web/pointerActionsPage.html" )
val pointerArea = driver . findElement ( By . id ( "pointerArea" ))
Actions ( driver )
. setActivePointer ( PointerInput . Kind . PEN , "default pen" )
. moveToElement ( pointerArea )
. clickAndHold ()
. moveByOffset ( 2 , 2 )
. release ()
. perform ()
val moves = driver . findElements ( By . className ( "pointermove" ))
val moveTo = getPropertyInfo ( moves . get ( 0 ))
val down = getPropertyInfo ( driver . findElement ( By . className ( "pointerdown" )))
val moveBy = getPropertyInfo ( moves . get ( 1 ))
val up = getPropertyInfo ( driver . findElement ( By . className ( "pointerup" )))
val rect = pointerArea . getRect ()
val centerX = Math . floor ( rect . width . toDouble () / 2 + rect . getX ()). toInt ()
val centerY = Math . floor ( rect . height . toDouble () / 2 + rect . getY ()). toInt ()
Assertions . assertEquals ( "-1" , moveTo . get ( "button" ))
Assertions . assertEquals ( "pen" , moveTo . get ( "pointerType" ))
Assertions . assertEquals ( centerX . toString (), moveTo . get ( "pageX" ))
Assertions . assertEquals ( centerY . toString (), moveTo . get ( "pageY" ))
Assertions . assertEquals ( "0" , down . get ( "button" ))
Assertions . assertEquals ( "pen" , down . get ( "pointerType" ))
Assertions . assertEquals ( centerX . toString (), down . get ( "pageX" ))
Assertions . assertEquals ( centerY . toString (), down . get ( "pageY" ))
Assertions . assertEquals ( "-1" , moveBy . get ( "button" ))
Assertions . assertEquals ( "pen" , moveBy . get ( "pointerType" ))
Assertions . assertEquals (( centerX + 2 ). toString (), moveBy . get ( "pageX" ))
Assertions . assertEquals (( centerY + 2 ). toString (), moveBy . get ( "pageY" ))
Assertions . assertEquals ( "0" , up . get ( "button" ))
Assertions . assertEquals ( "pen" , up . get ( "pointerType" ))
Assertions . assertEquals (( centerX + 2 ). toString (), up . get ( "pageX" ))
Assertions . assertEquals (( centerY + 2 ). toString (), up . get ( "pageY" ))
}
@Test
fun setPointerEventProperties () {
driver . get ( "https://selenium.dev/selenium/web/pointerActionsPage.html" )
val pointerArea = driver . findElement ( By . id ( "pointerArea" ))
val pen = PointerInput ( PointerInput . Kind . PEN , "default pen" )
val eventProperties = PointerInput . eventProperties ()
. setTiltX (- 72 )
. setTiltY ( 9 )
. setTwist ( 86 )
val origin = PointerInput . Origin . fromElement ( pointerArea )
val actionListPen = Sequence ( pen , 0 )
. addAction ( pen . createPointerMove ( Duration . ZERO , origin , 0 , 0 ))
. addAction ( pen . createPointerDown ( 0 ))
. addAction ( pen . createPointerMove ( Duration . ZERO , origin , 2 , 2 , eventProperties ))
. addAction ( pen . createPointerUp ( 0 ))
( driver as RemoteWebDriver ). perform ( listOf ( actionListPen ))
val moves = driver . findElements ( By . className ( "pointermove" ))
val moveTo = getPropertyInfo ( moves . get ( 0 ))
val down = getPropertyInfo ( driver . findElement ( By . className ( "pointerdown" )))
val moveBy = getPropertyInfo ( moves . get ( 1 ))
val up = getPropertyInfo ( driver . findElement ( By . className ( "pointerup" )))
val rect = pointerArea . getRect ()
val centerX = Math . floor ( rect . width . toDouble () / 2 + rect . getX ()). toInt ()
val centerY = Math . floor ( rect . height . toDouble () / 2 + rect . getY ()). toInt ()
Assertions . assertEquals ( "-1" , moveTo . get ( "button" ))
Assertions . assertEquals ( "pen" , moveTo . get ( "pointerType" ))
Assertions . assertEquals ( centerX . toString (), moveTo . get ( "pageX" ))
Assertions . assertEquals ( centerY . toString (), moveTo . get ( "pageY" ))
Assertions . assertEquals ( "0" , down . get ( "button" ))
Assertions . assertEquals ( "pen" , down . get ( "pointerType" ))
Assertions . assertEquals ( centerX . toString (), down . get ( "pageX" ))
Assertions . assertEquals ( centerY . toString (), down . get ( "pageY" ))
Assertions . assertEquals ( "-1" , moveBy . get ( "button" ))
Assertions . assertEquals ( "pen" , moveBy . get ( "pointerType" ))
Assertions . assertEquals (( centerX + 2 ). toString (), moveBy . get ( "pageX" ))
Assertions . assertEquals (( centerY + 2 ). toString (), moveBy . get ( "pageY" ))
Assertions . assertEquals ( "0" , up . get ( "button" ))
Assertions . assertEquals ( "pen" , up . get ( "pointerType" ))
Assertions . assertEquals (( centerX + 2 ). toString (), up . get ( "pageX" ))
Assertions . assertEquals (( centerY + 2 ). toString (), up . get ( "pageY" ))
Assertions . assertEquals ( "-72" , moveBy . get ( "tiltX" ))
Assertions . assertEquals ( "9" , moveBy . get ( "tiltY" ))
Assertions . assertEquals ( "86" , moveBy . get ( "twist" ))
}
fun getPropertyInfo ( element : WebElement ): Map < String , String > {
var text = element . getText ()
text = text . substring ( text . indexOf ( " " )+ 1 )
return text . split ( ", " )
. map { it . split ( ": " ) }
. map { it . first () to it . last () }
. toMap ()
}
}
Adicionando Atributos de Evento de Ponteiro Selenium v4.2
Java
Python
CSharp
Ruby
JavaScript
Kotlin WebElement pointerArea = driver . findElement ( By . id ( "pointerArea" ));
PointerInput pen = new PointerInput ( PointerInput . Kind . PEN , "default pen" );
PointerInput . PointerEventProperties eventProperties = PointerInput . eventProperties ()
. setTiltX ( - 72 )
. setTiltY ( 9 )
. setTwist ( 86 );
PointerInput . Origin origin = PointerInput . Origin . fromElement ( pointerArea );
Sequence actionListPen = new Sequence ( pen , 0 )
. addAction ( pen . createPointerMove ( Duration . ZERO , origin , 0 , 0 ))
. addAction ( pen . createPointerDown ( 0 ))
. addAction ( pen . createPointerMove ( Duration . ZERO , origin , 2 , 2 , eventProperties ))
. addAction ( pen . createPointerUp ( 0 ));
(( RemoteWebDriver ) driver ). perform ( Collections . singletonList ( actionListPen ));
Show full example 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.Rectangle ;
import org.openqa.selenium.WebElement ;
import org.openqa.selenium.interactions.Actions ;
import org.openqa.selenium.interactions.PointerInput ;
import org.openqa.selenium.interactions.Sequence ;
import org.openqa.selenium.remote.RemoteWebDriver ;
import java.time.Duration ;
import java.util.Arrays ;
import java.util.Collections ;
import java.util.List ;
import java.util.Map ;
import java.util.stream.Collectors ;
public class PenTest extends BaseChromeTest {
@Test
public void usePen () {
driver . get ( "https://www.selenium.dev/selenium/web/pointerActionsPage.html" );
WebElement pointerArea = driver . findElement ( By . id ( "pointerArea" ));
new Actions ( driver )
. setActivePointer ( PointerInput . Kind . PEN , "default pen" )
. moveToElement ( pointerArea )
. clickAndHold ()
. moveByOffset ( 2 , 2 )
. release ()
. perform ();
List < WebElement > moves = driver . findElements ( By . className ( "pointermove" ));
Map < String , String > moveTo = getPropertyInfo ( moves . get ( 0 ));
Map < String , String > down = getPropertyInfo ( driver . findElement ( By . className ( "pointerdown" )));
Map < String , String > moveBy = getPropertyInfo ( moves . get ( 1 ));
Map < String , String > up = getPropertyInfo ( driver . findElement ( By . className ( "pointerup" )));
Rectangle rect = pointerArea . getRect ();
int centerX = ( int ) Math . floor ( rect . width / 2 + rect . getX ());
int centerY = ( int ) Math . floor ( rect . height / 2 + rect . getY ());
Assertions . assertEquals ( "-1" , moveTo . get ( "button" ));
Assertions . assertEquals ( "pen" , moveTo . get ( "pointerType" ));
Assertions . assertEquals ( String . valueOf ( centerX ), moveTo . get ( "pageX" ));
Assertions . assertEquals ( String . valueOf ( centerY ), moveTo . get ( "pageY" ));
Assertions . assertEquals ( "0" , down . get ( "button" ));
Assertions . assertEquals ( "pen" , down . get ( "pointerType" ));
Assertions . assertEquals ( String . valueOf ( centerX ), down . get ( "pageX" ));
Assertions . assertEquals ( String . valueOf ( centerY ), down . get ( "pageY" ));
Assertions . assertEquals ( "-1" , moveBy . get ( "button" ));
Assertions . assertEquals ( "pen" , moveBy . get ( "pointerType" ));
Assertions . assertEquals ( String . valueOf ( centerX + 2 ), moveBy . get ( "pageX" ));
Assertions . assertEquals ( String . valueOf ( centerY + 2 ), moveBy . get ( "pageY" ));
Assertions . assertEquals ( "0" , up . get ( "button" ));
Assertions . assertEquals ( "pen" , up . get ( "pointerType" ));
Assertions . assertEquals ( String . valueOf ( centerX + 2 ), up . get ( "pageX" ));
Assertions . assertEquals ( String . valueOf ( centerY + 2 ), up . get ( "pageY" ));
}
@Test
public void setPointerEventProperties () {
driver . get ( "https://selenium.dev/selenium/web/pointerActionsPage.html" );
WebElement pointerArea = driver . findElement ( By . id ( "pointerArea" ));
PointerInput pen = new PointerInput ( PointerInput . Kind . PEN , "default pen" );
PointerInput . PointerEventProperties eventProperties = PointerInput . eventProperties ()
. setTiltX ( - 72 )
. setTiltY ( 9 )
. setTwist ( 86 );
PointerInput . Origin origin = PointerInput . Origin . fromElement ( pointerArea );
Sequence actionListPen = new Sequence ( pen , 0 )
. addAction ( pen . createPointerMove ( Duration . ZERO , origin , 0 , 0 ))
. addAction ( pen . createPointerDown ( 0 ))
. addAction ( pen . createPointerMove ( Duration . ZERO , origin , 2 , 2 , eventProperties ))
. addAction ( pen . createPointerUp ( 0 ));
(( RemoteWebDriver ) driver ). perform ( Collections . singletonList ( actionListPen ));
List < WebElement > moves = driver . findElements ( By . className ( "pointermove" ));
Map < String , String > moveTo = getPropertyInfo ( moves . get ( 0 ));
Map < String , String > down = getPropertyInfo ( driver . findElement ( By . className ( "pointerdown" )));
Map < String , String > moveBy = getPropertyInfo ( moves . get ( 1 ));
Map < String , String > up = getPropertyInfo ( driver . findElement ( By . className ( "pointerup" )));
Rectangle rect = pointerArea . getRect ();
int centerX = ( int ) Math . floor ( rect . width / 2 + rect . getX ());
int centerY = ( int ) Math . floor ( rect . height / 2 + rect . getY ());
Assertions . assertEquals ( "-1" , moveTo . get ( "button" ));
Assertions . assertEquals ( "pen" , moveTo . get ( "pointerType" ));
Assertions . assertEquals ( String . valueOf ( centerX ), moveTo . get ( "pageX" ));
Assertions . assertEquals ( String . valueOf ( centerY ), moveTo . get ( "pageY" ));
Assertions . assertEquals ( "0" , down . get ( "button" ));
Assertions . assertEquals ( "pen" , down . get ( "pointerType" ));
Assertions . assertEquals ( String . valueOf ( centerX ), down . get ( "pageX" ));
Assertions . assertEquals ( String . valueOf ( centerY ), down . get ( "pageY" ));
Assertions . assertEquals ( "-1" , moveBy . get ( "button" ));
Assertions . assertEquals ( "pen" , moveBy . get ( "pointerType" ));
Assertions . assertEquals ( String . valueOf ( centerX + 2 ), moveBy . get ( "pageX" ));
Assertions . assertEquals ( String . valueOf ( centerY + 2 ), moveBy . get ( "pageY" ));
Assertions . assertEquals ( "-72" , moveBy . get ( "tiltX" ));
Assertions . assertEquals ( "9" , moveBy . get ( "tiltY" ));
Assertions . assertEquals ( "86" , moveBy . get ( "twist" ));
Assertions . assertEquals ( "0" , up . get ( "button" ));
Assertions . assertEquals ( "pen" , up . get ( "pointerType" ));
Assertions . assertEquals ( String . valueOf ( centerX + 2 ), up . get ( "pageX" ));
Assertions . assertEquals ( String . valueOf ( centerY + 2 ), up . get ( "pageY" ));
}
private Map < String , String > getPropertyInfo ( WebElement element ) {
String text = element . getText ();
text = text . substring ( text . indexOf ( ' ' ) + 1 );
return Arrays . stream ( text . split ( ", " ))
. map ( s -> s . split ( ": " ))
. collect ( Collectors . toMap (
a -> a [ 0 ] ,
a -> a [ 1 ]
));
}
}
pointer_area = driver . find_element ( By . ID , "pointerArea" )
pen_input = PointerInput ( POINTER_PEN , "default pen" )
action = ActionBuilder ( driver , mouse = pen_input )
action . pointer_action \
. move_to ( pointer_area ) \
. pointer_down () \
. move_by ( 2 , 2 , tilt_x =- 72 , tilt_y = 9 , twist = 86 ) \
. pointer_up ( 0 )
action . perform ()
Show full example import math
from selenium.webdriver.common.actions.action_builder import ActionBuilder
from selenium.webdriver.common.actions.interaction import POINTER_PEN
from selenium.webdriver.common.actions.pointer_input import PointerInput
from selenium.webdriver.common.by import By
def test_use_pen ( driver ):
driver . get ( 'https://www.selenium.dev/selenium/web/pointerActionsPage.html' )
pointer_area = driver . find_element ( By . ID , "pointerArea" )
pen_input = PointerInput ( POINTER_PEN , "default pen" )
action = ActionBuilder ( driver , mouse = pen_input )
action . pointer_action \
. move_to ( pointer_area ) \
. pointer_down () \
. move_by ( 2 , 2 ) \
. pointer_up ()
action . perform ()
moves = driver . find_elements ( By . CLASS_NAME , "pointermove" )
move_to = properties ( moves [ 0 ])
down = properties ( driver . find_element ( By . CLASS_NAME , "pointerdown" ))
move_by = properties ( moves [ 1 ])
up = properties ( driver . find_element ( By . CLASS_NAME , "pointerup" ))
rect = pointer_area . rect
center_x = rect [ "x" ] + rect [ "width" ] / 2
center_y = rect [ "y" ] + rect [ "height" ] / 2
assert move_to [ "button" ] == "-1"
assert move_to [ "pointerType" ] == "pen"
assert move_to [ "pageX" ] == str ( math . floor ( center_x ))
assert move_to [ "pageY" ] == str ( math . floor ( center_y ))
assert down [ "button" ] == "0"
assert down [ "pointerType" ] == "pen"
assert down [ "pageX" ] == str ( math . floor ( center_x ))
assert down [ "pageY" ] == str ( math . floor ( center_y ))
assert move_by [ "button" ] == "-1"
assert move_by [ "pointerType" ] == "pen"
assert move_by [ "pageX" ] == str ( math . floor ( center_x + 2 ))
assert move_by [ "pageY" ] == str ( math . floor ( center_y + 2 ))
assert up [ "button" ] == "0"
assert up [ "pointerType" ] == "pen"
assert up [ "pageX" ] == str ( math . floor ( center_x + 2 ))
assert up [ "pageY" ] == str ( math . floor ( center_y + 2 ))
def test_set_pointer_event_properties ( driver ):
driver . get ( 'https://www.selenium.dev/selenium/web/pointerActionsPage.html' )
pointer_area = driver . find_element ( By . ID , "pointerArea" )
pen_input = PointerInput ( POINTER_PEN , "default pen" )
action = ActionBuilder ( driver , mouse = pen_input )
action . pointer_action \
. move_to ( pointer_area ) \
. pointer_down () \
. move_by ( 2 , 2 , tilt_x =- 72 , tilt_y = 9 , twist = 86 ) \
. pointer_up ( 0 )
action . perform ()
moves = driver . find_elements ( By . CLASS_NAME , "pointermove" )
move_to = properties ( moves [ 0 ])
down = properties ( driver . find_element ( By . CLASS_NAME , "pointerdown" ))
move_by = properties ( moves [ 1 ])
up = properties ( driver . find_element ( By . CLASS_NAME , "pointerup" ))
rect = pointer_area . rect
center_x = rect [ "x" ] + rect [ "width" ] / 2
center_y = rect [ "y" ] + rect [ "height" ] / 2
assert move_to [ "button" ] == "-1"
assert move_to [ "pointerType" ] == "pen"
assert move_to [ "pageX" ] == str ( math . floor ( center_x ))
assert move_to [ "pageY" ] == str ( math . floor ( center_y ))
assert down [ "button" ] == "0"
assert down [ "pointerType" ] == "pen"
assert down [ "pageX" ] == str ( math . floor ( center_x ))
assert down [ "pageY" ] == str ( math . floor ( center_y ))
assert move_by [ "button" ] == "-1"
assert move_by [ "pointerType" ] == "pen"
assert move_by [ "pageX" ] == str ( math . floor ( center_x + 2 ))
assert move_by [ "pageY" ] == str ( math . floor ( center_y + 2 ))
assert move_by [ "tiltX" ] == "-72"
assert move_by [ "tiltY" ] == "9"
assert move_by [ "twist" ] == "86"
assert up [ "button" ] == "0"
assert up [ "pointerType" ] == "pen"
assert up [ "pageX" ] == str ( math . floor ( center_x + 2 ))
assert up [ "pageY" ] == str ( math . floor ( center_y + 2 ))
def properties ( element ):
kv = element . text . split ( ' ' , 1 )[ 1 ] . split ( ', ' )
return { x [ 0 ]: x [ 1 ] for x in list ( map ( lambda item : item . split ( ': ' ), kv ))}
IWebElement pointerArea = driver . FindElement ( By . Id ( "pointerArea" ));
ActionBuilder actionBuilder = new ActionBuilder ();
PointerInputDevice pen = new PointerInputDevice ( PointerKind . Pen , "default pen" );
PointerInputDevice . PointerEventProperties properties = new PointerInputDevice . PointerEventProperties () {
TiltX = - 72 ,
TiltY = 9 ,
Twist = 86 ,
};
actionBuilder . AddAction ( pen . CreatePointerMove ( pointerArea , 0 , 0 , TimeSpan . FromMilliseconds ( 800 )));
actionBuilder . AddAction ( pen . CreatePointerDown ( MouseButton . Left ));
actionBuilder . AddAction ( pen . CreatePointerMove ( CoordinateOrigin . Pointer ,
2 , 2 , TimeSpan . Zero , properties ));
actionBuilder . AddAction ( pen . CreatePointerUp ( MouseButton . Left ));
(( IActionExecutor ) driver ). PerformActions ( actionBuilder . ToActionSequenceList ());
Show full example using System ;
using System.Collections.Generic ;
using System.Drawing ;
using System.Linq ;
using Microsoft.VisualStudio.TestTools.UnitTesting ;
using OpenQA.Selenium ;
using OpenQA.Selenium.Interactions ;
namespace SeleniumDocs.ActionsAPI
{
[TestClass]
public class PenTest : BaseChromeTest
{
[TestMethod]
public void UsePen ()
{
driver . Url = "https://selenium.dev/selenium/web/pointerActionsPage.html" ;
IWebElement pointerArea = driver . FindElement ( By . Id ( "pointerArea" ));
ActionBuilder actionBuilder = new ActionBuilder ();
PointerInputDevice pen = new PointerInputDevice ( PointerKind . Pen , "default pen" );
actionBuilder . AddAction ( pen . CreatePointerMove ( pointerArea , 0 , 0 , TimeSpan . FromMilliseconds ( 800 )));
actionBuilder . AddAction ( pen . CreatePointerDown ( MouseButton . Left ));
actionBuilder . AddAction ( pen . CreatePointerMove ( CoordinateOrigin . Pointer ,
2 , 2 , TimeSpan . Zero ));
actionBuilder . AddAction ( pen . CreatePointerUp ( MouseButton . Left ));
(( IActionExecutor ) driver ). PerformActions ( actionBuilder . ToActionSequenceList ());
var moves = driver . FindElements ( By . ClassName ( "pointermove" ));
var moveTo = getProperties ( moves . ElementAt ( 0 ));
var down = getProperties ( driver . FindElement ( By . ClassName ( "pointerdown" )));
var moveBy = getProperties ( moves . ElementAt ( 1 ));
var up = getProperties ( driver . FindElement ( By . ClassName ( "pointerup" )));
Point location = pointerArea . Location ;
Size size = pointerArea . Size ;
decimal centerX = location . X + size . Width / 2 ;
decimal centerY = location . Y + size . Height / 2 ;
Assert . AreEqual ( "-1" , moveTo [ "button" ]);
Assert . AreEqual ( "pen" , moveTo [ "pointerType" ]);
Assert . IsTrue ( VerifyEquivalent ( centerX , moveTo [ "pageX" ]));
Assert . IsTrue ( VerifyEquivalent ( centerY , moveTo [ "pageY" ]));
Assert . AreEqual ( "0" , down [ "button" ]);
Assert . AreEqual ( "pen" , down [ "pointerType" ]);
Assert . IsTrue ( VerifyEquivalent ( centerX , down [ "pageX" ]));
Assert . IsTrue ( VerifyEquivalent ( centerY , down [ "pageY" ]));
Assert . AreEqual ( "-1" , moveBy [ "button" ]);
Assert . AreEqual ( "pen" , moveBy [ "pointerType" ]);
Assert . IsTrue ( VerifyEquivalent ( centerX + 2 , moveBy [ "pageX" ]));
Assert . IsTrue ( VerifyEquivalent ( centerY + 2 , moveBy [ "pageY" ]));
Assert . AreEqual ( "0" , up [ "button" ]);
Assert . AreEqual ( "pen" , up [ "pointerType" ]);
Assert . IsTrue ( VerifyEquivalent ( centerX + 2 , up [ "pageX" ]));
Assert . IsTrue ( VerifyEquivalent ( centerY + 2 , up [ "pageY" ]));
}
[TestMethod]
public void SetPointerEventProperties ()
{
driver . Url = "https://selenium.dev/selenium/web/pointerActionsPage.html" ;
IWebElement pointerArea = driver . FindElement ( By . Id ( "pointerArea" ));
ActionBuilder actionBuilder = new ActionBuilder ();
PointerInputDevice pen = new PointerInputDevice ( PointerKind . Pen , "default pen" );
PointerInputDevice . PointerEventProperties properties = new PointerInputDevice . PointerEventProperties () {
TiltX = - 72 ,
TiltY = 9 ,
Twist = 86 ,
};
actionBuilder . AddAction ( pen . CreatePointerMove ( pointerArea , 0 , 0 , TimeSpan . FromMilliseconds ( 800 )));
actionBuilder . AddAction ( pen . CreatePointerDown ( MouseButton . Left ));
actionBuilder . AddAction ( pen . CreatePointerMove ( CoordinateOrigin . Pointer ,
2 , 2 , TimeSpan . Zero , properties ));
actionBuilder . AddAction ( pen . CreatePointerUp ( MouseButton . Left ));
(( IActionExecutor ) driver ). PerformActions ( actionBuilder . ToActionSequenceList ());
var moves = driver . FindElements ( By . ClassName ( "pointermove" ));
var moveTo = getProperties ( moves . ElementAt ( 0 ));
var down = getProperties ( driver . FindElement ( By . ClassName ( "pointerdown" )));
var moveBy = getProperties ( moves . ElementAt ( 1 ));
var up = getProperties ( driver . FindElement ( By . ClassName ( "pointerup" )));
Point location = pointerArea . Location ;
Size size = pointerArea . Size ;
decimal centerX = location . X + size . Width / 2 ;
decimal centerY = location . Y + size . Height / 2 ;
Assert . AreEqual ( "-1" , moveTo [ "button" ]);
Assert . AreEqual ( "pen" , moveTo [ "pointerType" ]);
Assert . IsTrue ( VerifyEquivalent ( centerX , moveTo [ "pageX" ]));
Assert . IsTrue ( VerifyEquivalent ( centerY , moveTo [ "pageY" ]));
Assert . AreEqual ( "0" , down [ "button" ]);
Assert . AreEqual ( "pen" , down [ "pointerType" ]);
Assert . IsTrue ( VerifyEquivalent ( centerX , down [ "pageX" ]));
Assert . IsTrue ( VerifyEquivalent ( centerY , down [ "pageY" ]));
Assert . AreEqual ( "-1" , moveBy [ "button" ]);
Assert . AreEqual ( "pen" , moveBy [ "pointerType" ]);
Assert . IsTrue ( VerifyEquivalent ( centerX + 2 , moveBy [ "pageX" ]));
Assert . IsTrue ( VerifyEquivalent ( centerY + 2 , moveBy [ "pageY" ]));
Assert . AreEqual ((- 72 ). ToString (), moveBy [ "tiltX" ]);
Assert . AreEqual (( 9 ). ToString (), moveBy [ "tiltY" ]);
Assert . AreEqual (( 86 ). ToString (), moveBy [ "twist" ]);
Assert . AreEqual ( "0" , up [ "button" ]);
Assert . AreEqual ( "pen" , up [ "pointerType" ]);
Assert . IsTrue ( VerifyEquivalent ( centerX + 2 , up [ "pageX" ]));
Assert . IsTrue ( VerifyEquivalent ( centerY + 2 , up [ "pageY" ]));
}
private Dictionary < string , string > getProperties ( IWebElement element )
{
var str = element . Text ;
str = str [( str . Split ()[ 0 ]. Length + 1 )..];
IEnumerable < string []> keyValue = str . Split ( ", " ). Select ( part => part . Split ( ":" ));
return keyValue . ToDictionary ( split => split [ 0 ]. Trim (), split => split [ 1 ]. Trim ());
}
private bool VerifyEquivalent ( decimal expected , string actual )
{
var absolute = Math . Abs ( expected - decimal . Parse ( actual ));
if ( absolute <= 1 )
{
return true ;
}
throw new Exception ( "Expected: " + expected + "; but received: " + actual );
}
}
}
pointer_area = driver . find_element ( id : 'pointerArea' )
driver . action ( devices : :pen )
. move_to ( pointer_area )
. pointer_down
. move_by ( 2 , 2 , tilt_x : - 72 , tilt_y : 9 , twist : 86 )
. pointer_up
. perform
Show full example # frozen_string_literal: true
require 'spec_helper'
RSpec . describe 'Pen' do
let ( :driver ) { start_session }
it 'uses a pen' do
driver . get 'https://www.selenium.dev/selenium/web/pointerActionsPage.html'
pointer_area = driver . find_element ( id : 'pointerArea' )
driver . action ( devices : :pen )
. move_to ( pointer_area )
. pointer_down
. move_by ( 2 , 2 )
. pointer_up
. perform
moves = driver . find_elements ( class : 'pointermove' )
move_to = properties ( moves [ 0 ] )
down = properties ( driver . find_element ( class : 'pointerdown' ))
move_by = properties ( moves [ 1 ] )
up = properties ( driver . find_element ( class : 'pointerup' ))
rect = pointer_area . rect
center_x = rect . x + ( rect . width / 2 )
center_y = rect . y + ( rect . height / 2 )
expect ( move_to ) . to include ( 'button' => '-1' ,
'pointerType' => 'pen' ,
'pageX' => center_x . to_s ,
'pageY' => center_y . floor . to_s )
expect ( down ) . to include ( 'button' => '0' ,
'pointerType' => 'pen' ,
'pageX' => center_x . to_s ,
'pageY' => center_y . floor . to_s )
expect ( move_by ) . to include ( 'button' => '-1' ,
'pointerType' => 'pen' ,
'pageX' => ( center_x + 2 ) . to_s ,
'pageY' => ( center_y + 2 ) . floor . to_s )
expect ( up ) . to include ( 'button' => '0' ,
'pointerType' => 'pen' ,
'pageX' => ( center_x + 2 ) . to_s ,
'pageY' => ( center_y + 2 ) . floor . to_s )
end
it 'sets pointer event attributes' do
driver . get 'https://www.selenium.dev/selenium/web/pointerActionsPage.html'
pointer_area = driver . find_element ( id : 'pointerArea' )
driver . action ( devices : :pen )
. move_to ( pointer_area )
. pointer_down
. move_by ( 2 , 2 , tilt_x : - 72 , tilt_y : 9 , twist : 86 )
. pointer_up
. perform
moves = driver . find_elements ( class : 'pointermove' )
move_to = properties ( moves [ 0 ] )
down = properties ( driver . find_element ( class : 'pointerdown' ))
move_by = properties ( moves [ 1 ] )
up = properties ( driver . find_element ( class : 'pointerup' ))
rect = pointer_area . rect
center_x = rect . x + ( rect . width / 2 )
center_y = rect . y + ( rect . height / 2 )
expect ( move_to ) . to include ( 'button' => '-1' ,
'pointerType' => 'pen' ,
'pageX' => center_x . to_s ,
'pageY' => center_y . floor . to_s )
expect ( down ) . to include ( 'button' => '0' ,
'pointerType' => 'pen' ,
'pageX' => center_x . to_s ,
'pageY' => center_y . floor . to_s )
expect ( move_by ) . to include ( 'button' => '-1' ,
'pointerType' => 'pen' ,
'pageX' => ( center_x + 2 ) . to_s ,
'pageY' => ( center_y + 2 ) . floor . to_s ,
'tiltX' => - 72 . to_s ,
'tiltY' => 9 . to_s ,
'twist' => 86 . to_s )
expect ( up ) . to include ( 'button' => '0' ,
'pointerType' => 'pen' ,
'pageX' => ( center_x + 2 ) . to_s ,
'pageY' => ( center_y + 2 ) . floor . to_s )
end
def properties ( element )
element . text . sub ( /.*?\s/ , '' ) . split ( ',' ) . to_h { | item | item . lstrip . split ( /\s*:\s*/ ) }
end
end
val pointerArea = driver . findElement ( By . id ( "pointerArea" ))
val pen = PointerInput ( PointerInput . Kind . PEN , "default pen" )
val eventProperties = PointerInput . eventProperties ()
. setTiltX (- 72 )
. setTiltY ( 9 )
. setTwist ( 86 )
val origin = PointerInput . Origin . fromElement ( pointerArea )
val actionListPen = Sequence ( pen , 0 )
. addAction ( pen . createPointerMove ( Duration . ZERO , origin , 0 , 0 ))
. addAction ( pen . createPointerDown ( 0 ))
. addAction ( pen . createPointerMove ( Duration . ZERO , origin , 2 , 2 , eventProperties ))
. addAction ( pen . createPointerUp ( 0 ))
( driver as RemoteWebDriver ). perform ( listOf ( actionListPen ))
Show full example 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.Rectangle
import org.openqa.selenium.WebElement
import org.openqa.selenium.interactions.Actions
import org.openqa.selenium.interactions.PointerInput
import org.openqa.selenium.interactions.Sequence
import org.openqa.selenium.remote.RemoteWebDriver
import kotlin.collections.Map
import java.time.Duration
class PenTest : BaseTest () {
@Test
fun usePen () {
driver . get ( "https://www.selenium.dev/selenium/web/pointerActionsPage.html" )
val pointerArea = driver . findElement ( By . id ( "pointerArea" ))
Actions ( driver )
. setActivePointer ( PointerInput . Kind . PEN , "default pen" )
. moveToElement ( pointerArea )
. clickAndHold ()
. moveByOffset ( 2 , 2 )
. release ()
. perform ()
val moves = driver . findElements ( By . className ( "pointermove" ))
val moveTo = getPropertyInfo ( moves . get ( 0 ))
val down = getPropertyInfo ( driver . findElement ( By . className ( "pointerdown" )))
val moveBy = getPropertyInfo ( moves . get ( 1 ))
val up = getPropertyInfo ( driver . findElement ( By . className ( "pointerup" )))
val rect = pointerArea . getRect ()
val centerX = Math . floor ( rect . width . toDouble () / 2 + rect . getX ()). toInt ()
val centerY = Math . floor ( rect . height . toDouble () / 2 + rect . getY ()). toInt ()
Assertions . assertEquals ( "-1" , moveTo . get ( "button" ))
Assertions . assertEquals ( "pen" , moveTo . get ( "pointerType" ))
Assertions . assertEquals ( centerX . toString (), moveTo . get ( "pageX" ))
Assertions . assertEquals ( centerY . toString (), moveTo . get ( "pageY" ))
Assertions . assertEquals ( "0" , down . get ( "button" ))
Assertions . assertEquals ( "pen" , down . get ( "pointerType" ))
Assertions . assertEquals ( centerX . toString (), down . get ( "pageX" ))
Assertions . assertEquals ( centerY . toString (), down . get ( "pageY" ))
Assertions . assertEquals ( "-1" , moveBy . get ( "button" ))
Assertions . assertEquals ( "pen" , moveBy . get ( "pointerType" ))
Assertions . assertEquals (( centerX + 2 ). toString (), moveBy . get ( "pageX" ))
Assertions . assertEquals (( centerY + 2 ). toString (), moveBy . get ( "pageY" ))
Assertions . assertEquals ( "0" , up . get ( "button" ))
Assertions . assertEquals ( "pen" , up . get ( "pointerType" ))
Assertions . assertEquals (( centerX + 2 ). toString (), up . get ( "pageX" ))
Assertions . assertEquals (( centerY + 2 ). toString (), up . get ( "pageY" ))
}
@Test
fun setPointerEventProperties () {
driver . get ( "https://selenium.dev/selenium/web/pointerActionsPage.html" )
val pointerArea = driver . findElement ( By . id ( "pointerArea" ))
val pen = PointerInput ( PointerInput . Kind . PEN , "default pen" )
val eventProperties = PointerInput . eventProperties ()
. setTiltX (- 72 )
. setTiltY ( 9 )
. setTwist ( 86 )
val origin = PointerInput . Origin . fromElement ( pointerArea )
val actionListPen = Sequence ( pen , 0 )
. addAction ( pen . createPointerMove ( Duration . ZERO , origin , 0 , 0 ))
. addAction ( pen . createPointerDown ( 0 ))
. addAction ( pen . createPointerMove ( Duration . ZERO , origin , 2 , 2 , eventProperties ))
. addAction ( pen . createPointerUp ( 0 ))
( driver as RemoteWebDriver ). perform ( listOf ( actionListPen ))
val moves = driver . findElements ( By . className ( "pointermove" ))
val moveTo = getPropertyInfo ( moves . get ( 0 ))
val down = getPropertyInfo ( driver . findElement ( By . className ( "pointerdown" )))
val moveBy = getPropertyInfo ( moves . get ( 1 ))
val up = getPropertyInfo ( driver . findElement ( By . className ( "pointerup" )))
val rect = pointerArea . getRect ()
val centerX = Math . floor ( rect . width . toDouble () / 2 + rect . getX ()). toInt ()
val centerY = Math . floor ( rect . height . toDouble () / 2 + rect . getY ()). toInt ()
Assertions . assertEquals ( "-1" , moveTo . get ( "button" ))
Assertions . assertEquals ( "pen" , moveTo . get ( "pointerType" ))
Assertions . assertEquals ( centerX . toString (), moveTo . get ( "pageX" ))
Assertions . assertEquals ( centerY . toString (), moveTo . get ( "pageY" ))
Assertions . assertEquals ( "0" , down . get ( "button" ))
Assertions . assertEquals ( "pen" , down . get ( "pointerType" ))
Assertions . assertEquals ( centerX . toString (), down . get ( "pageX" ))
Assertions . assertEquals ( centerY . toString (), down . get ( "pageY" ))
Assertions . assertEquals ( "-1" , moveBy . get ( "button" ))
Assertions . assertEquals ( "pen" , moveBy . get ( "pointerType" ))
Assertions . assertEquals (( centerX + 2 ). toString (), moveBy . get ( "pageX" ))
Assertions . assertEquals (( centerY + 2 ). toString (), moveBy . get ( "pageY" ))
Assertions . assertEquals ( "0" , up . get ( "button" ))
Assertions . assertEquals ( "pen" , up . get ( "pointerType" ))
Assertions . assertEquals (( centerX + 2 ). toString (), up . get ( "pageX" ))
Assertions . assertEquals (( centerY + 2 ). toString (), up . get ( "pageY" ))
Assertions . assertEquals ( "-72" , moveBy . get ( "tiltX" ))
Assertions . assertEquals ( "9" , moveBy . get ( "tiltY" ))
Assertions . assertEquals ( "86" , moveBy . get ( "twist" ))
}
fun getPropertyInfo ( element : WebElement ): Map < String , String > {
var text = element . getText ()
text = text . substring ( text . indexOf ( " " )+ 1 )
return text . split ( ", " )
. map { it . split ( ": " ) }
. map { it . first () to it . last () }
. toMap ()
}
}
4 - Ações de Roda de Rolagem “Uma representação de um dispositivo de entrada de roda de rolagem para interagir com uma página da web.”
Selenium v4.2
Chromium Only
Existem 5 cenários para rolagem em uma página.
Rolagem até o Elemento Este é o cenário mais comum. Diferentemente dos métodos tradicionais de clique e envio de teclas, a classe de ações não rolará automaticamente o elemento de destino para a visualização, portanto, este método precisará ser usado se os elementos não estiverem dentro da janela de visualização.
Este método recebe um elemento da web como único argumento.
Independentemente de o elemento estar acima ou abaixo da tela de visualização atual, a janela de visualização será rolada de forma que a parte inferior do elemento esteja na parte inferior da tela.
Java
Python
CSharp
Ruby
JavaScript
Kotlin WebElement iframe = driver . findElement ( By . tagName ( "iframe" ));
new Actions ( driver )
. scrollToElement ( iframe )
. perform ();
Show full example 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.JavascriptExecutor ;
import org.openqa.selenium.WebElement ;
import org.openqa.selenium.interactions.Actions ;
import org.openqa.selenium.interactions.WheelInput ;
public class WheelTest extends BaseChromeTest {
@Test
public void shouldScrollToElement () {
driver . get ( "https://www.selenium.dev/selenium/web/scrolling_tests/frame_with_nested_scrolling_frame_out_of_view.html" );
WebElement iframe = driver . findElement ( By . tagName ( "iframe" ));
new Actions ( driver )
. scrollToElement ( iframe )
. perform ();
Assertions . assertTrue ( inViewport ( iframe ));
}
@Test
public void shouldScrollFromViewportByGivenAmount () {
driver . get ( "https://www.selenium.dev/selenium/web/scrolling_tests/frame_with_nested_scrolling_frame_out_of_view.html" );
WebElement footer = driver . findElement ( By . tagName ( "footer" ));
int deltaY = footer . getRect (). y ;
new Actions ( driver )
. scrollByAmount ( 0 , deltaY )
. perform ();
Assertions . assertTrue ( inViewport ( footer ));
}
@Test
public void shouldScrollFromElementByGivenAmount () {
driver . get ( "https://www.selenium.dev/selenium/web/scrolling_tests/frame_with_nested_scrolling_frame_out_of_view.html" );
WebElement iframe = driver . findElement ( By . tagName ( "iframe" ));
WheelInput . ScrollOrigin scrollOrigin = WheelInput . ScrollOrigin . fromElement ( iframe );
new Actions ( driver )
. scrollFromOrigin ( scrollOrigin , 0 , 200 )
. perform ();
driver . switchTo (). frame ( iframe );
WebElement checkbox = driver . findElement ( By . name ( "scroll_checkbox" ));
Assertions . assertTrue ( inViewport ( checkbox ));
}
@Test
public void shouldScrollFromElementByGivenAmountWithOffset () {
driver . get ( "https://www.selenium.dev/selenium/web/scrolling_tests/frame_with_nested_scrolling_frame_out_of_view.html" );
WebElement footer = driver . findElement ( By . tagName ( "footer" ));
WheelInput . ScrollOrigin scrollOrigin = WheelInput . ScrollOrigin . fromElement ( footer , 0 , - 50 );
new Actions ( driver )
. scrollFromOrigin ( scrollOrigin , 0 , 200 )
. perform ();
WebElement iframe = driver . findElement ( By . tagName ( "iframe" ));
driver . switchTo (). frame ( iframe );
WebElement checkbox = driver . findElement ( By . name ( "scroll_checkbox" ));
Assertions . assertTrue ( inViewport ( checkbox ));
}
@Test
public void shouldScrollFromViewportByGivenAmountFromOrigin () {
driver . get ( "https://www.selenium.dev/selenium/web/scrolling_tests/frame_with_nested_scrolling_frame.html" );
WheelInput . ScrollOrigin scrollOrigin = WheelInput . ScrollOrigin . fromViewport ( 10 , 10 );
new Actions ( driver )
. scrollFromOrigin ( scrollOrigin , 0 , 200 )
. perform ();
WebElement iframe = driver . findElement ( By . tagName ( "iframe" ));
driver . switchTo (). frame ( iframe );
WebElement checkbox = driver . findElement ( By . name ( "scroll_checkbox" ));
Assertions . assertTrue ( inViewport ( checkbox ));
}
private boolean inViewport ( WebElement element ) {
String script =
"for(var e=arguments[0],f=e.offsetTop,t=e.offsetLeft,o=e.offsetWidth,n=e.offsetHeight;\n"
+ "e.offsetParent;)f+=(e=e.offsetParent).offsetTop,t+=e.offsetLeft;\n"
+ "return f<window.pageYOffset+window.innerHeight&&t<window.pageXOffset+window.innerWidth&&f+n>\n"
+ "window.pageYOffset&&t+o>window.pageXOffset" ;
return ( boolean ) (( JavascriptExecutor ) driver ). executeScript ( script , element );
}
}
iframe = driver . find_element ( By . TAG_NAME , "iframe" )
ActionChains ( driver ) \
. scroll_to_element ( iframe ) \
. perform ()
Show full example from time import sleep
from selenium.webdriver import ActionChains
from selenium.webdriver.common.by import By
from selenium.webdriver.common.actions.wheel_input import ScrollOrigin
def test_can_scroll_to_element ( driver ):
driver . get ( "https://selenium.dev/selenium/web/scrolling_tests/frame_with_nested_scrolling_frame_out_of_view.html" )
iframe = driver . find_element ( By . TAG_NAME , "iframe" )
ActionChains ( driver ) \
. scroll_to_element ( iframe ) \
. perform ()
assert _in_viewport ( driver , iframe )
def test_can_scroll_from_viewport_by_amount ( driver ):
driver . get ( "https://selenium.dev/selenium/web/scrolling_tests/frame_with_nested_scrolling_frame_out_of_view.html" )
footer = driver . find_element ( By . TAG_NAME , "footer" )
delta_y = footer . rect [ 'y' ]
ActionChains ( driver ) \
. scroll_by_amount ( 0 , delta_y ) \
. perform ()
sleep ( 0.5 )
assert _in_viewport ( driver , footer )
def test_can_scroll_from_element_by_amount ( driver ):
driver . get ( "https://selenium.dev/selenium/web/scrolling_tests/frame_with_nested_scrolling_frame_out_of_view.html" )
iframe = driver . find_element ( By . TAG_NAME , "iframe" )
scroll_origin = ScrollOrigin . from_element ( iframe )
ActionChains ( driver ) \
. scroll_from_origin ( scroll_origin , 0 , 200 ) \
. perform ()
sleep ( 0.5 )
driver . switch_to . frame ( iframe )
checkbox = driver . find_element ( By . NAME , "scroll_checkbox" )
assert _in_viewport ( driver , checkbox )
def test_can_scroll_from_element_with_offset_by_amount ( driver ):
driver . get ( "https://selenium.dev/selenium/web/scrolling_tests/frame_with_nested_scrolling_frame_out_of_view.html" )
footer = driver . find_element ( By . TAG_NAME , "footer" )
scroll_origin = ScrollOrigin . from_element ( footer , 0 , - 50 )
ActionChains ( driver ) \
. scroll_from_origin ( scroll_origin , 0 , 200 ) \
. perform ()
sleep ( 0.5 )
iframe = driver . find_element ( By . TAG_NAME , "iframe" )
driver . switch_to . frame ( iframe )
checkbox = driver . find_element ( By . NAME , "scroll_checkbox" )
assert _in_viewport ( driver , checkbox )
def test_can_scroll_from_viewport_with_offset_by_amount ( driver ):
driver . get ( "https://selenium.dev/selenium/web/scrolling_tests/frame_with_nested_scrolling_frame.html" )
scroll_origin = ScrollOrigin . from_viewport ( 10 , 10 )
ActionChains ( driver ) \
. scroll_from_origin ( scroll_origin , 0 , 200 ) \
. perform ()
sleep ( 0.5 )
iframe = driver . find_element ( By . TAG_NAME , "iframe" )
driver . switch_to . frame ( iframe )
checkbox = driver . find_element ( By . NAME , "scroll_checkbox" )
assert _in_viewport ( driver , checkbox )
def _in_viewport ( driver , element ):
script = (
"for(var e=arguments[0],f=e.offsetTop,t=e.offsetLeft,o=e.offsetWidth,n=e.offsetHeight; \n "
"e.offsetParent;)f+=(e=e.offsetParent).offsetTop,t+=e.offsetLeft; \n "
"return f<window.pageYOffset+window.innerHeight&&t<window.pageXOffset+window.innerWidth&&f+n> \n "
"window.pageYOffset&&t+o>window.pageXOffset"
)
return driver . execute_script ( script , element )
IWebElement iframe = driver . FindElement ( By . TagName ( "iframe" ));
new Actions ( driver )
. ScrollToElement ( iframe )
. Perform ();
Show full example using System ;
using Microsoft.VisualStudio.TestTools.UnitTesting ;
using OpenQA.Selenium ;
using OpenQA.Selenium.Interactions ;
namespace SeleniumDocs.ActionsAPI
{
[TestClass]
public class WheelTest : BaseChromeTest
{
[TestMethod]
public void ShouldAllowScrollingToAnElement ()
{
driver . Url =
"https://selenium.dev/selenium/web/scrolling_tests/frame_with_nested_scrolling_frame_out_of_view.html" ;
IWebElement iframe = driver . FindElement ( By . TagName ( "iframe" ));
new Actions ( driver )
. ScrollToElement ( iframe )
. Perform ();
Assert . IsTrue ( IsInViewport ( iframe ));
}
[TestMethod]
public void ShouldAllowScrollingFromViewportByGivenAmount ()
{
driver . Url =
"https://selenium.dev/selenium/web/scrolling_tests/frame_with_nested_scrolling_frame_out_of_view.html" ;
IWebElement footer = driver . FindElement ( By . TagName ( "footer" ));
int deltaY = footer . Location . Y ;
new Actions ( driver )
. ScrollByAmount ( 0 , deltaY )
. Perform ();
Assert . IsTrue ( IsInViewport ( footer ));
}
[TestMethod]
public void ShouldScrollFromElementByGivenAmount ()
{
driver . Url =
"https://selenium.dev/selenium/web/scrolling_tests/frame_with_nested_scrolling_frame_out_of_view.html" ;
IWebElement iframe = driver . FindElement ( By . TagName ( "iframe" ));
WheelInputDevice . ScrollOrigin scrollOrigin = new WheelInputDevice . ScrollOrigin
{
Element = iframe
};
new Actions ( driver )
. ScrollFromOrigin ( scrollOrigin , 0 , 200 )
. Perform ();
driver . SwitchTo (). Frame ( iframe );
IWebElement checkbox = driver . FindElement ( By . Name ( "scroll_checkbox" ));
Assert . IsTrue ( IsInViewport ( checkbox ));
}
[TestMethod]
public void ShouldAllowScrollingFromElementByGivenAmountWithOffset ()
{
driver . Url =
"https://selenium.dev/selenium/web/scrolling_tests/frame_with_nested_scrolling_frame_out_of_view.html" ;
IWebElement footer = driver . FindElement ( By . TagName ( "footer" ));
var scrollOrigin = new WheelInputDevice . ScrollOrigin
{
Element = footer ,
XOffset = 0 ,
YOffset = - 50
};
new Actions ( driver )
. ScrollFromOrigin ( scrollOrigin , 0 , 200 )
. Perform ();
IWebElement iframe = driver . FindElement ( By . TagName ( "iframe" ));
driver . SwitchTo (). Frame ( iframe );
IWebElement checkbox = driver . FindElement ( By . Name ( "scroll_checkbox" ));
Assert . IsTrue ( IsInViewport ( checkbox ));
}
[TestMethod]
public void ShouldAllowScrollingFromViewportByGivenAmountFromOrigin ()
{
driver . Url =
"https://selenium.dev/selenium/web/scrolling_tests/frame_with_nested_scrolling_frame.html" ;
var scrollOrigin = new WheelInputDevice . ScrollOrigin
{
Viewport = true ,
XOffset = 10 ,
YOffset = 10
};
new Actions ( driver )
. ScrollFromOrigin ( scrollOrigin , 0 , 200 )
. Perform ();
IWebElement iframe = driver . FindElement ( By . TagName ( "iframe" ));
driver . SwitchTo (). Frame ( iframe );
IWebElement checkbox = driver . FindElement ( By . Name ( "scroll_checkbox" ));
Assert . IsTrue ( IsInViewport ( checkbox ));
}
private bool IsInViewport ( IWebElement element )
{
String script =
"for(var e=arguments[0],f=e.offsetTop,t=e.offsetLeft,o=e.offsetWidth,n=e.offsetHeight;\n"
+ "e.offsetParent;)f+=(e=e.offsetParent).offsetTop,t+=e.offsetLeft;\n"
+ "return f<window.pageYOffset+window.innerHeight&&t<window.pageXOffset+window.innerWidth&&f+n>\n"
+ "window.pageYOffset&&t+o>window.pageXOffset" ;
IJavaScriptExecutor javascriptDriver = this . driver as IJavaScriptExecutor ;
return ( bool ) javascriptDriver . ExecuteScript ( script , element );
}
}
}
iframe = driver . find_element ( tag_name : 'iframe' )
driver . action
. scroll_to ( iframe )
. perform
Show full example # frozen_string_literal: true
require 'spec_helper'
RSpec . describe 'Scrolling' do
let ( :driver ) { start_session }
it 'scrolls to element' do
driver . get ( 'https://selenium.dev/selenium/web/scrolling_tests/frame_with_nested_scrolling_frame_out_of_view.html' )
iframe = driver . find_element ( tag_name : 'iframe' )
driver . action
. scroll_to ( iframe )
. perform
expect ( in_viewport? ( iframe )) . to eq true
end
it 'scrolls by given amount' do
driver . get ( 'https://selenium.dev/selenium/web/scrolling_tests/frame_with_nested_scrolling_frame_out_of_view.html' )
footer = driver . find_element ( tag_name : 'footer' )
delta_y = footer . rect . y
driver . action
. scroll_by ( 0 , delta_y )
. perform
expect ( in_viewport? ( footer )) . to eq true
end
it 'scrolls from element by given amount' do
driver . get ( 'https://selenium.dev/selenium/web/scrolling_tests/frame_with_nested_scrolling_frame_out_of_view.html' )
iframe = driver . find_element ( tag_name : 'iframe' )
scroll_origin = Selenium :: WebDriver :: WheelActions :: ScrollOrigin . element ( iframe )
driver . action
. scroll_from ( scroll_origin , 0 , 200 )
. perform
driver . switch_to . frame ( iframe )
checkbox = driver . find_element ( name : 'scroll_checkbox' )
expect ( in_viewport? ( checkbox )) . to eq true
end
it 'scrolls from element by given amount with offset' do
driver . get ( 'https://selenium.dev/selenium/web/scrolling_tests/frame_with_nested_scrolling_frame_out_of_view.html' )
footer = driver . find_element ( tag_name : 'footer' )
scroll_origin = Selenium :: WebDriver :: WheelActions :: ScrollOrigin . element ( footer , 0 , - 50 )
driver . action
. scroll_from ( scroll_origin , 0 , 200 )
. perform
iframe = driver . find_element ( tag_name : 'iframe' )
driver . switch_to . frame ( iframe )
checkbox = driver . find_element ( name : 'scroll_checkbox' )
expect ( in_viewport? ( checkbox )) . to eq true
end
it 'scrolls by given amount with offset' do
driver . get ( 'https://selenium.dev/selenium/web/scrolling_tests/frame_with_nested_scrolling_frame.html' )
scroll_origin = Selenium :: WebDriver :: WheelActions :: ScrollOrigin . viewport ( 10 , 10 )
driver . action
. scroll_from ( scroll_origin , 0 , 200 )
. perform
iframe = driver . find_element ( tag_name : 'iframe' )
driver . switch_to . frame ( iframe )
checkbox = driver . find_element ( name : 'scroll_checkbox' )
expect ( in_viewport? ( checkbox )) . to eq true
end
end
def in_viewport? ( element )
in_viewport = <<~ IN_VIEWPORT
for ( var e = arguments [ 0 ] , f = e . offsetTop , t = e . offsetLeft , o = e . offsetWidth , n = e . offsetHeight ;
e . offsetParent ;) f += ( e = e . offsetParent ) . offsetTop , t += e . offsetLeft ;
return f < window . pageYOffset + window . innerHeight && t < window . pageXOffset + window . innerWidth && f + n >
window . pageYOffset && t + o > window . pageXOffset
IN_VIEWPORT
driver . execute_script ( in_viewport , element )
end
const iframe = await driver . findElement ( By . css ( "iframe" ))
await driver . actions ()
. scroll ( 0 , 0 , 0 , 0 , iframe )
. perform ()
Show full example const { By , Browser , Builder } = require ( 'selenium-webdriver' )
const assert = require ( 'assert' )
describe ( 'Actions API - Wheel Tests' , function () {
let driver
before ( async function () {
driver = await new Builder (). forBrowser ( 'chrome' ). build ();
})
after ( async () => await driver . quit ())
it ( 'Scroll to element' , async function () {
await driver . get ( "https://www.selenium.dev/selenium/web/scrolling_tests/frame_with_nested_scrolling_frame_out_of_view.html" )
const iframe = await driver . findElement ( By . css ( "iframe" ))
await driver . actions ()
. scroll ( 0 , 0 , 0 , 0 , iframe )
. perform ()
assert . ok ( await inViewport ( iframe ))
})
it ( 'Scroll by given amount' , async function () {
await driver . get ( "https://www.selenium.dev/selenium/web/scrolling_tests/frame_with_nested_scrolling_frame_out_of_view.html" )
const footer = await driver . findElement ( By . css ( "footer" ))
const deltaY = ( await footer . getRect ()). y
await driver . actions ()
. scroll ( 0 , 0 , 0 , deltaY )
. perform ()
await driver . sleep ( 500 )
assert . ok ( await inViewport ( footer ))
})
it ( 'Scroll from an element by a given amount' , async function () {
await driver . get ( "https://www.selenium.dev/selenium/web/scrolling_tests/frame_with_nested_scrolling_frame_out_of_view.html" )
const iframe = await driver . findElement ( By . css ( "iframe" ))
await driver . actions ()
. scroll ( 0 , 0 , 0 , 200 , iframe )
. perform ()
await driver . sleep ( 500 )
await driver . switchTo (). frame ( iframe )
const checkbox = await driver . findElement ( By . name ( 'scroll_checkbox' ))
assert . ok ( await inViewport ( checkbox ))
})
it ( 'Scroll from an element with an offset' , async function () {
await driver . get ( "https://www.selenium.dev/selenium/web/scrolling_tests/frame_with_nested_scrolling_frame_out_of_view.html" )
const iframe = await driver . findElement ( By . css ( "iframe" ))
const footer = await driver . findElement ( By . css ( "footer" ))
await driver . actions ()
. scroll ( 0 , - 50 , 0 , 200 , footer )
. perform ()
await driver . sleep ( 500 )
await driver . switchTo (). frame ( iframe )
const checkbox = await driver . findElement ( By . name ( 'scroll_checkbox' ))
assert . ok ( await inViewport ( checkbox ))
})
it ( 'Scroll from an offset of origin (element) by given amount' , async function () {
await driver . get ( "https://www.selenium.dev/selenium/web/scrolling_tests/frame_with_nested_scrolling_frame.html" )
const iframe = await driver . findElement ( By . css ( "iframe" ))
await driver . actions ()
. scroll ( 10 , 10 , 0 , 200 )
. perform ()
await driver . sleep ( 500 )
await driver . switchTo (). frame ( iframe )
const checkbox = await driver . findElement ( By . name ( 'scroll_checkbox' ))
assert . ok ( await inViewport ( checkbox ))
})
function inViewport ( element ) {
return driver . executeScript ( "for(var e=arguments[0],f=e.offsetTop,t=e.offsetLeft,o=e.offsetWidth,n=e.offsetHeight;\ne.offsetParent;)f+=(e=e.offsetParent).offsetTop,t+=e.offsetLeft;\nreturn f<window.pageYOffset+window.innerHeight&&t<window.pageXOffset+window.innerWidth&&f+n>\nwindow.pageYOffset&&t+o>window.pageXOffset" , element )
}
})
val iframe = driver . findElement ( By . tagName ( "iframe" ))
Actions ( driver )
. scrollToElement ( iframe )
. perform ()
Show full example 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.JavascriptExecutor
import org.openqa.selenium.WebElement
import org.openqa.selenium.interactions.Actions
import org.openqa.selenium.interactions.WheelInput
class WheelTest : BaseTest () {
@Test
fun shouldScrollToElement () {
driver . get ( "https://www.selenium.dev/selenium/web/scrolling_tests/frame_with_nested_scrolling_frame_out_of_view.html" )
val iframe = driver . findElement ( By . tagName ( "iframe" ))
Actions ( driver )
. scrollToElement ( iframe )
. perform ()
Assertions . assertTrue ( inViewport ( iframe ))
}
@Test
fun shouldScrollFromViewportByGivenAmount () {
driver . get ( "https://www.selenium.dev/selenium/web/scrolling_tests/frame_with_nested_scrolling_frame_out_of_view.html" )
val footer = driver . findElement ( By . tagName ( "footer" ))
val deltaY = footer . getRect (). y
Actions ( driver )
. scrollByAmount ( 0 , deltaY )
. perform ()
Assertions . assertTrue ( inViewport ( footer ))
}
@Test
fun shouldScrollFromElementByGivenAmount () {
driver . get ( "https://www.selenium.dev/selenium/web/scrolling_tests/frame_with_nested_scrolling_frame_out_of_view.html" )
val iframe = driver . findElement ( By . tagName ( "iframe" ))
val scrollOrigin = WheelInput . ScrollOrigin . fromElement ( iframe )
Actions ( driver )
. scrollFromOrigin ( scrollOrigin , 0 , 200 )
. perform ()
driver . switchTo (). frame ( iframe )
val checkbox = driver . findElement ( By . name ( "scroll_checkbox" ))
Assertions . assertTrue ( inViewport ( checkbox ))
}
@Test
fun shouldScrollFromElementByGivenAmountWithOffset () {
driver . get ( "https://www.selenium.dev/selenium/web/scrolling_tests/frame_with_nested_scrolling_frame_out_of_view.html" )
val footer = driver . findElement ( By . tagName ( "footer" ))
val scrollOrigin = WheelInput . ScrollOrigin . fromElement ( footer , 0 , - 50 )
Actions ( driver )
. scrollFromOrigin ( scrollOrigin , 0 , 200 )
. perform ()
val iframe = driver . findElement ( By . tagName ( "iframe" ))
driver . switchTo (). frame ( iframe )
val checkbox = driver . findElement ( By . name ( "scroll_checkbox" ))
Assertions . assertTrue ( inViewport ( checkbox ))
}
@Test
fun shouldScrollFromViewportByGivenAmountFromOrigin () {
driver . get ( "https://www.selenium.dev/selenium/web/scrolling_tests/frame_with_nested_scrolling_frame.html" )
val scrollOrigin = WheelInput . ScrollOrigin . fromViewport ( 10 , 10 )
Actions ( driver )
. scrollFromOrigin ( scrollOrigin , 0 , 200 )
. perform ()
val iframe = driver . findElement ( By . tagName ( "iframe" ))
driver . switchTo (). frame ( iframe )
val checkbox = driver . findElement ( By . name ( "scroll_checkbox" ))
Assertions . assertTrue ( inViewport ( checkbox ))
}
fun inViewport ( element : WebElement ): Boolean {
val script = "for(var e=arguments[0],f=e.offsetTop,t=e.offsetLeft,o=e.offsetWidth,n=e.offsetHeight; \n e.offsetParent;)f+=(e=e.offsetParent).offsetTop,t+=e.offsetLeft; \n return f<window.pageYOffset+window.innerHeight&&t<window.pageXOffset+window.innerWidth&&f+n> \n window.pageYOffset&&t+o>window.pageXOffset"
return ( driver as JavascriptExecutor ). executeScript ( script , element ) as Boolean
}
}
Rolar por uma Quantidade Especificada Este é o segundo cenário mais comum para a rolagem. Passe um valor delta x e um valor delta y para o quanto rolar nas direções direita e para baixo. Valores negativos representam esquerda e para cima, respectivamente.
Java
Python
CSharp
Ruby
JavaScript
Kotlin WebElement footer = driver . findElement ( By . tagName ( "footer" ));
int deltaY = footer . getRect (). y ;
new Actions ( driver )
. scrollByAmount ( 0 , deltaY )
. perform ();
Show full example 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.JavascriptExecutor ;
import org.openqa.selenium.WebElement ;
import org.openqa.selenium.interactions.Actions ;
import org.openqa.selenium.interactions.WheelInput ;
public class WheelTest extends BaseChromeTest {
@Test
public void shouldScrollToElement () {
driver . get ( "https://www.selenium.dev/selenium/web/scrolling_tests/frame_with_nested_scrolling_frame_out_of_view.html" );
WebElement iframe = driver . findElement ( By . tagName ( "iframe" ));
new Actions ( driver )
. scrollToElement ( iframe )
. perform ();
Assertions . assertTrue ( inViewport ( iframe ));
}
@Test
public void shouldScrollFromViewportByGivenAmount () {
driver . get ( "https://www.selenium.dev/selenium/web/scrolling_tests/frame_with_nested_scrolling_frame_out_of_view.html" );
WebElement footer = driver . findElement ( By . tagName ( "footer" ));
int deltaY = footer . getRect (). y ;
new Actions ( driver )
. scrollByAmount ( 0 , deltaY )
. perform ();
Assertions . assertTrue ( inViewport ( footer ));
}
@Test
public void shouldScrollFromElementByGivenAmount () {
driver . get ( "https://www.selenium.dev/selenium/web/scrolling_tests/frame_with_nested_scrolling_frame_out_of_view.html" );
WebElement iframe = driver . findElement ( By . tagName ( "iframe" ));
WheelInput . ScrollOrigin scrollOrigin = WheelInput . ScrollOrigin . fromElement ( iframe );
new Actions ( driver )
. scrollFromOrigin ( scrollOrigin , 0 , 200 )
. perform ();
driver . switchTo (). frame ( iframe );
WebElement checkbox = driver . findElement ( By . name ( "scroll_checkbox" ));
Assertions . assertTrue ( inViewport ( checkbox ));
}
@Test
public void shouldScrollFromElementByGivenAmountWithOffset () {
driver . get ( "https://www.selenium.dev/selenium/web/scrolling_tests/frame_with_nested_scrolling_frame_out_of_view.html" );
WebElement footer = driver . findElement ( By . tagName ( "footer" ));
WheelInput . ScrollOrigin scrollOrigin = WheelInput . ScrollOrigin . fromElement ( footer , 0 , - 50 );
new Actions ( driver )
. scrollFromOrigin ( scrollOrigin , 0 , 200 )
. perform ();
WebElement iframe = driver . findElement ( By . tagName ( "iframe" ));
driver . switchTo (). frame ( iframe );
WebElement checkbox = driver . findElement ( By . name ( "scroll_checkbox" ));
Assertions . assertTrue ( inViewport ( checkbox ));
}
@Test
public void shouldScrollFromViewportByGivenAmountFromOrigin () {
driver . get ( "https://www.selenium.dev/selenium/web/scrolling_tests/frame_with_nested_scrolling_frame.html" );
WheelInput . ScrollOrigin scrollOrigin = WheelInput . ScrollOrigin . fromViewport ( 10 , 10 );
new Actions ( driver )
. scrollFromOrigin ( scrollOrigin , 0 , 200 )
. perform ();
WebElement iframe = driver . findElement ( By . tagName ( "iframe" ));
driver . switchTo (). frame ( iframe );
WebElement checkbox = driver . findElement ( By . name ( "scroll_checkbox" ));
Assertions . assertTrue ( inViewport ( checkbox ));
}
private boolean inViewport ( WebElement element ) {
String script =
"for(var e=arguments[0],f=e.offsetTop,t=e.offsetLeft,o=e.offsetWidth,n=e.offsetHeight;\n"
+ "e.offsetParent;)f+=(e=e.offsetParent).offsetTop,t+=e.offsetLeft;\n"
+ "return f<window.pageYOffset+window.innerHeight&&t<window.pageXOffset+window.innerWidth&&f+n>\n"
+ "window.pageYOffset&&t+o>window.pageXOffset" ;
return ( boolean ) (( JavascriptExecutor ) driver ). executeScript ( script , element );
}
}
footer = driver . find_element ( By . TAG_NAME , "footer" )
delta_y = footer . rect [ 'y' ]
ActionChains ( driver ) \
. scroll_by_amount ( 0 , delta_y ) \
. perform ()
Show full example from time import sleep
from selenium.webdriver import ActionChains
from selenium.webdriver.common.by import By
from selenium.webdriver.common.actions.wheel_input import ScrollOrigin
def test_can_scroll_to_element ( driver ):
driver . get ( "https://selenium.dev/selenium/web/scrolling_tests/frame_with_nested_scrolling_frame_out_of_view.html" )
iframe = driver . find_element ( By . TAG_NAME , "iframe" )
ActionChains ( driver ) \
. scroll_to_element ( iframe ) \
. perform ()
assert _in_viewport ( driver , iframe )
def test_can_scroll_from_viewport_by_amount ( driver ):
driver . get ( "https://selenium.dev/selenium/web/scrolling_tests/frame_with_nested_scrolling_frame_out_of_view.html" )
footer = driver . find_element ( By . TAG_NAME , "footer" )
delta_y = footer . rect [ 'y' ]
ActionChains ( driver ) \
. scroll_by_amount ( 0 , delta_y ) \
. perform ()
sleep ( 0.5 )
assert _in_viewport ( driver , footer )
def test_can_scroll_from_element_by_amount ( driver ):
driver . get ( "https://selenium.dev/selenium/web/scrolling_tests/frame_with_nested_scrolling_frame_out_of_view.html" )
iframe = driver . find_element ( By . TAG_NAME , "iframe" )
scroll_origin = ScrollOrigin . from_element ( iframe )
ActionChains ( driver ) \
. scroll_from_origin ( scroll_origin , 0 , 200 ) \
. perform ()
sleep ( 0.5 )
driver . switch_to . frame ( iframe )
checkbox = driver . find_element ( By . NAME , "scroll_checkbox" )
assert _in_viewport ( driver , checkbox )
def test_can_scroll_from_element_with_offset_by_amount ( driver ):
driver . get ( "https://selenium.dev/selenium/web/scrolling_tests/frame_with_nested_scrolling_frame_out_of_view.html" )
footer = driver . find_element ( By . TAG_NAME , "footer" )
scroll_origin = ScrollOrigin . from_element ( footer , 0 , - 50 )
ActionChains ( driver ) \
. scroll_from_origin ( scroll_origin , 0 , 200 ) \
. perform ()
sleep ( 0.5 )
iframe = driver . find_element ( By . TAG_NAME , "iframe" )
driver . switch_to . frame ( iframe )
checkbox = driver . find_element ( By . NAME , "scroll_checkbox" )
assert _in_viewport ( driver , checkbox )
def test_can_scroll_from_viewport_with_offset_by_amount ( driver ):
driver . get ( "https://selenium.dev/selenium/web/scrolling_tests/frame_with_nested_scrolling_frame.html" )
scroll_origin = ScrollOrigin . from_viewport ( 10 , 10 )
ActionChains ( driver ) \
. scroll_from_origin ( scroll_origin , 0 , 200 ) \
. perform ()
sleep ( 0.5 )
iframe = driver . find_element ( By . TAG_NAME , "iframe" )
driver . switch_to . frame ( iframe )
checkbox = driver . find_element ( By . NAME , "scroll_checkbox" )
assert _in_viewport ( driver , checkbox )
def _in_viewport ( driver , element ):
script = (
"for(var e=arguments[0],f=e.offsetTop,t=e.offsetLeft,o=e.offsetWidth,n=e.offsetHeight; \n "
"e.offsetParent;)f+=(e=e.offsetParent).offsetTop,t+=e.offsetLeft; \n "
"return f<window.pageYOffset+window.innerHeight&&t<window.pageXOffset+window.innerWidth&&f+n> \n "
"window.pageYOffset&&t+o>window.pageXOffset"
)
return driver . execute_script ( script , element )
IWebElement footer = driver . FindElement ( By . TagName ( "footer" ));
int deltaY = footer . Location . Y ;
new Actions ( driver )
. ScrollByAmount ( 0 , deltaY )
. Perform ();
Show full example using System ;
using Microsoft.VisualStudio.TestTools.UnitTesting ;
using OpenQA.Selenium ;
using OpenQA.Selenium.Interactions ;
namespace SeleniumDocs.ActionsAPI
{
[TestClass]
public class WheelTest : BaseChromeTest
{
[TestMethod]
public void ShouldAllowScrollingToAnElement ()
{
driver . Url =
"https://selenium.dev/selenium/web/scrolling_tests/frame_with_nested_scrolling_frame_out_of_view.html" ;
IWebElement iframe = driver . FindElement ( By . TagName ( "iframe" ));
new Actions ( driver )
. ScrollToElement ( iframe )
. Perform ();
Assert . IsTrue ( IsInViewport ( iframe ));
}
[TestMethod]
public void ShouldAllowScrollingFromViewportByGivenAmount ()
{
driver . Url =
"https://selenium.dev/selenium/web/scrolling_tests/frame_with_nested_scrolling_frame_out_of_view.html" ;
IWebElement footer = driver . FindElement ( By . TagName ( "footer" ));
int deltaY = footer . Location . Y ;
new Actions ( driver )
. ScrollByAmount ( 0 , deltaY )
. Perform ();
Assert . IsTrue ( IsInViewport ( footer ));
}
[TestMethod]
public void ShouldScrollFromElementByGivenAmount ()
{
driver . Url =
"https://selenium.dev/selenium/web/scrolling_tests/frame_with_nested_scrolling_frame_out_of_view.html" ;
IWebElement iframe = driver . FindElement ( By . TagName ( "iframe" ));
WheelInputDevice . ScrollOrigin scrollOrigin = new WheelInputDevice . ScrollOrigin
{
Element = iframe
};
new Actions ( driver )
. ScrollFromOrigin ( scrollOrigin , 0 , 200 )
. Perform ();
driver . SwitchTo (). Frame ( iframe );
IWebElement checkbox = driver . FindElement ( By . Name ( "scroll_checkbox" ));
Assert . IsTrue ( IsInViewport ( checkbox ));
}
[TestMethod]
public void ShouldAllowScrollingFromElementByGivenAmountWithOffset ()
{
driver . Url =
"https://selenium.dev/selenium/web/scrolling_tests/frame_with_nested_scrolling_frame_out_of_view.html" ;
IWebElement footer = driver . FindElement ( By . TagName ( "footer" ));
var scrollOrigin = new WheelInputDevice . ScrollOrigin
{
Element = footer ,
XOffset = 0 ,
YOffset = - 50
};
new Actions ( driver )
. ScrollFromOrigin ( scrollOrigin , 0 , 200 )
. Perform ();
IWebElement iframe = driver . FindElement ( By . TagName ( "iframe" ));
driver . SwitchTo (). Frame ( iframe );
IWebElement checkbox = driver . FindElement ( By . Name ( "scroll_checkbox" ));
Assert . IsTrue ( IsInViewport ( checkbox ));
}
[TestMethod]
public void ShouldAllowScrollingFromViewportByGivenAmountFromOrigin ()
{
driver . Url =
"https://selenium.dev/selenium/web/scrolling_tests/frame_with_nested_scrolling_frame.html" ;
var scrollOrigin = new WheelInputDevice . ScrollOrigin
{
Viewport = true ,
XOffset = 10 ,
YOffset = 10
};
new Actions ( driver )
. ScrollFromOrigin ( scrollOrigin , 0 , 200 )
. Perform ();
IWebElement iframe = driver . FindElement ( By . TagName ( "iframe" ));
driver . SwitchTo (). Frame ( iframe );
IWebElement checkbox = driver . FindElement ( By . Name ( "scroll_checkbox" ));
Assert . IsTrue ( IsInViewport ( checkbox ));
}
private bool IsInViewport ( IWebElement element )
{
String script =
"for(var e=arguments[0],f=e.offsetTop,t=e.offsetLeft,o=e.offsetWidth,n=e.offsetHeight;\n"
+ "e.offsetParent;)f+=(e=e.offsetParent).offsetTop,t+=e.offsetLeft;\n"
+ "return f<window.pageYOffset+window.innerHeight&&t<window.pageXOffset+window.innerWidth&&f+n>\n"
+ "window.pageYOffset&&t+o>window.pageXOffset" ;
IJavaScriptExecutor javascriptDriver = this . driver as IJavaScriptExecutor ;
return ( bool ) javascriptDriver . ExecuteScript ( script , element );
}
}
}
footer = driver . find_element ( tag_name : 'footer' )
delta_y = footer . rect . y
driver . action
. scroll_by ( 0 , delta_y )
. perform
Show full example # frozen_string_literal: true
require 'spec_helper'
RSpec . describe 'Scrolling' do
let ( :driver ) { start_session }
it 'scrolls to element' do
driver . get ( 'https://selenium.dev/selenium/web/scrolling_tests/frame_with_nested_scrolling_frame_out_of_view.html' )
iframe = driver . find_element ( tag_name : 'iframe' )
driver . action
. scroll_to ( iframe )
. perform
expect ( in_viewport? ( iframe )) . to eq true
end
it 'scrolls by given amount' do
driver . get ( 'https://selenium.dev/selenium/web/scrolling_tests/frame_with_nested_scrolling_frame_out_of_view.html' )
footer = driver . find_element ( tag_name : 'footer' )
delta_y = footer . rect . y
driver . action
. scroll_by ( 0 , delta_y )
. perform
expect ( in_viewport? ( footer )) . to eq true
end
it 'scrolls from element by given amount' do
driver . get ( 'https://selenium.dev/selenium/web/scrolling_tests/frame_with_nested_scrolling_frame_out_of_view.html' )
iframe = driver . find_element ( tag_name : 'iframe' )
scroll_origin = Selenium :: WebDriver :: WheelActions :: ScrollOrigin . element ( iframe )
driver . action
. scroll_from ( scroll_origin , 0 , 200 )
. perform
driver . switch_to . frame ( iframe )
checkbox = driver . find_element ( name : 'scroll_checkbox' )
expect ( in_viewport? ( checkbox )) . to eq true
end
it 'scrolls from element by given amount with offset' do
driver . get ( 'https://selenium.dev/selenium/web/scrolling_tests/frame_with_nested_scrolling_frame_out_of_view.html' )
footer = driver . find_element ( tag_name : 'footer' )
scroll_origin = Selenium :: WebDriver :: WheelActions :: ScrollOrigin . element ( footer , 0 , - 50 )
driver . action
. scroll_from ( scroll_origin , 0 , 200 )
. perform
iframe = driver . find_element ( tag_name : 'iframe' )
driver . switch_to . frame ( iframe )
checkbox = driver . find_element ( name : 'scroll_checkbox' )
expect ( in_viewport? ( checkbox )) . to eq true
end
it 'scrolls by given amount with offset' do
driver . get ( 'https://selenium.dev/selenium/web/scrolling_tests/frame_with_nested_scrolling_frame.html' )
scroll_origin = Selenium :: WebDriver :: WheelActions :: ScrollOrigin . viewport ( 10 , 10 )
driver . action
. scroll_from ( scroll_origin , 0 , 200 )
. perform
iframe = driver . find_element ( tag_name : 'iframe' )
driver . switch_to . frame ( iframe )
checkbox = driver . find_element ( name : 'scroll_checkbox' )
expect ( in_viewport? ( checkbox )) . to eq true
end
end
def in_viewport? ( element )
in_viewport = <<~ IN_VIEWPORT
for ( var e = arguments [ 0 ] , f = e . offsetTop , t = e . offsetLeft , o = e . offsetWidth , n = e . offsetHeight ;
e . offsetParent ;) f += ( e = e . offsetParent ) . offsetTop , t += e . offsetLeft ;
return f < window . pageYOffset + window . innerHeight && t < window . pageXOffset + window . innerWidth && f + n >
window . pageYOffset && t + o > window . pageXOffset
IN_VIEWPORT
driver . execute_script ( in_viewport , element )
end
const footer = await driver . findElement ( By . css ( "footer" ))
const deltaY = ( await footer . getRect ()). y
await driver . actions ()
. scroll ( 0 , 0 , 0 , deltaY )
. perform ()
Show full example const { By , Browser , Builder } = require ( 'selenium-webdriver' )
const assert = require ( 'assert' )
describe ( 'Actions API - Wheel Tests' , function () {
let driver
before ( async function () {
driver = await new Builder (). forBrowser ( 'chrome' ). build ();
})
after ( async () => await driver . quit ())
it ( 'Scroll to element' , async function () {
await driver . get ( "https://www.selenium.dev/selenium/web/scrolling_tests/frame_with_nested_scrolling_frame_out_of_view.html" )
const iframe = await driver . findElement ( By . css ( "iframe" ))
await driver . actions ()
. scroll ( 0 , 0 , 0 , 0 , iframe )
. perform ()
assert . ok ( await inViewport ( iframe ))
})
it ( 'Scroll by given amount' , async function () {
await driver . get ( "https://www.selenium.dev/selenium/web/scrolling_tests/frame_with_nested_scrolling_frame_out_of_view.html" )
const footer = await driver . findElement ( By . css ( "footer" ))
const deltaY = ( await footer . getRect ()). y
await driver . actions ()
. scroll ( 0 , 0 , 0 , deltaY )
. perform ()
await driver . sleep ( 500 )
assert . ok ( await inViewport ( footer ))
})
it ( 'Scroll from an element by a given amount' , async function () {
await driver . get ( "https://www.selenium.dev/selenium/web/scrolling_tests/frame_with_nested_scrolling_frame_out_of_view.html" )
const iframe = await driver . findElement ( By . css ( "iframe" ))
await driver . actions ()
. scroll ( 0 , 0 , 0 , 200 , iframe )
. perform ()
await driver . sleep ( 500 )
await driver . switchTo (). frame ( iframe )
const checkbox = await driver . findElement ( By . name ( 'scroll_checkbox' ))
assert . ok ( await inViewport ( checkbox ))
})
it ( 'Scroll from an element with an offset' , async function () {
await driver . get ( "https://www.selenium.dev/selenium/web/scrolling_tests/frame_with_nested_scrolling_frame_out_of_view.html" )
const iframe = await driver . findElement ( By . css ( "iframe" ))
const footer = await driver . findElement ( By . css ( "footer" ))
await driver . actions ()
. scroll ( 0 , - 50 , 0 , 200 , footer )
. perform ()
await driver . sleep ( 500 )
await driver . switchTo (). frame ( iframe )
const checkbox = await driver . findElement ( By . name ( 'scroll_checkbox' ))
assert . ok ( await inViewport ( checkbox ))
})
it ( 'Scroll from an offset of origin (element) by given amount' , async function () {
await driver . get ( "https://www.selenium.dev/selenium/web/scrolling_tests/frame_with_nested_scrolling_frame.html" )
const iframe = await driver . findElement ( By . css ( "iframe" ))
await driver . actions ()
. scroll ( 10 , 10 , 0 , 200 )
. perform ()
await driver . sleep ( 500 )
await driver . switchTo (). frame ( iframe )
const checkbox = await driver . findElement ( By . name ( 'scroll_checkbox' ))
assert . ok ( await inViewport ( checkbox ))
})
function inViewport ( element ) {
return driver . executeScript ( "for(var e=arguments[0],f=e.offsetTop,t=e.offsetLeft,o=e.offsetWidth,n=e.offsetHeight;\ne.offsetParent;)f+=(e=e.offsetParent).offsetTop,t+=e.offsetLeft;\nreturn f<window.pageYOffset+window.innerHeight&&t<window.pageXOffset+window.innerWidth&&f+n>\nwindow.pageYOffset&&t+o>window.pageXOffset" , element )
}
})
val footer = driver . findElement ( By . tagName ( "footer" ))
val deltaY = footer . getRect (). y
Actions ( driver )
. scrollByAmount ( 0 , deltaY )
. perform ()
Show full example 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.JavascriptExecutor
import org.openqa.selenium.WebElement
import org.openqa.selenium.interactions.Actions
import org.openqa.selenium.interactions.WheelInput
class WheelTest : BaseTest () {
@Test
fun shouldScrollToElement () {
driver . get ( "https://www.selenium.dev/selenium/web/scrolling_tests/frame_with_nested_scrolling_frame_out_of_view.html" )
val iframe = driver . findElement ( By . tagName ( "iframe" ))
Actions ( driver )
. scrollToElement ( iframe )
. perform ()
Assertions . assertTrue ( inViewport ( iframe ))
}
@Test
fun shouldScrollFromViewportByGivenAmount () {
driver . get ( "https://www.selenium.dev/selenium/web/scrolling_tests/frame_with_nested_scrolling_frame_out_of_view.html" )
val footer = driver . findElement ( By . tagName ( "footer" ))
val deltaY = footer . getRect (). y
Actions ( driver )
. scrollByAmount ( 0 , deltaY )
. perform ()
Assertions . assertTrue ( inViewport ( footer ))
}
@Test
fun shouldScrollFromElementByGivenAmount () {
driver . get ( "https://www.selenium.dev/selenium/web/scrolling_tests/frame_with_nested_scrolling_frame_out_of_view.html" )
val iframe = driver . findElement ( By . tagName ( "iframe" ))
val scrollOrigin = WheelInput . ScrollOrigin . fromElement ( iframe )
Actions ( driver )
. scrollFromOrigin ( scrollOrigin , 0 , 200 )
. perform ()
driver . switchTo (). frame ( iframe )
val checkbox = driver . findElement ( By . name ( "scroll_checkbox" ))
Assertions . assertTrue ( inViewport ( checkbox ))
}
@Test
fun shouldScrollFromElementByGivenAmountWithOffset () {
driver . get ( "https://www.selenium.dev/selenium/web/scrolling_tests/frame_with_nested_scrolling_frame_out_of_view.html" )
val footer = driver . findElement ( By . tagName ( "footer" ))
val scrollOrigin = WheelInput . ScrollOrigin . fromElement ( footer , 0 , - 50 )
Actions ( driver )
. scrollFromOrigin ( scrollOrigin , 0 , 200 )
. perform ()
val iframe = driver . findElement ( By . tagName ( "iframe" ))
driver . switchTo (). frame ( iframe )
val checkbox = driver . findElement ( By . name ( "scroll_checkbox" ))
Assertions . assertTrue ( inViewport ( checkbox ))
}
@Test
fun shouldScrollFromViewportByGivenAmountFromOrigin () {
driver . get ( "https://www.selenium.dev/selenium/web/scrolling_tests/frame_with_nested_scrolling_frame.html" )
val scrollOrigin = WheelInput . ScrollOrigin . fromViewport ( 10 , 10 )
Actions ( driver )
. scrollFromOrigin ( scrollOrigin , 0 , 200 )
. perform ()
val iframe = driver . findElement ( By . tagName ( "iframe" ))
driver . switchTo (). frame ( iframe )
val checkbox = driver . findElement ( By . name ( "scroll_checkbox" ))
Assertions . assertTrue ( inViewport ( checkbox ))
}
fun inViewport ( element : WebElement ): Boolean {
val script = "for(var e=arguments[0],f=e.offsetTop,t=e.offsetLeft,o=e.offsetWidth,n=e.offsetHeight; \n e.offsetParent;)f+=(e=e.offsetParent).offsetTop,t+=e.offsetLeft; \n return f<window.pageYOffset+window.innerHeight&&t<window.pageXOffset+window.innerWidth&&f+n> \n window.pageYOffset&&t+o>window.pageXOffset"
return ( driver as JavascriptExecutor ). executeScript ( script , element ) as Boolean
}
}
Rolagem a partir de um Elemento por uma Quantidade Especificada" Este cenário é efetivamente uma combinação dos dois métodos mencionados anteriormente.
Para executar isso, use o método “Rolar a Partir de”, que recebe 3 argumentos. O primeiro representa o ponto de origem, que designamos como o elemento, e os dois seguintes são os valores delta x e delta y.
Se o elemento estiver fora da janela de visualização, ele será rolado para a parte inferior da tela e, em seguida, a página será rolada pelos valores delta x e delta y fornecidos.
Java
Python
CSharp
Ruby
JavaScript
Kotlin WebElement iframe = driver . findElement ( By . tagName ( "iframe" ));
WheelInput . ScrollOrigin scrollOrigin = WheelInput . ScrollOrigin . fromElement ( iframe );
new Actions ( driver )
. scrollFromOrigin ( scrollOrigin , 0 , 200 )
. perform ();
Show full example 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.JavascriptExecutor ;
import org.openqa.selenium.WebElement ;
import org.openqa.selenium.interactions.Actions ;
import org.openqa.selenium.interactions.WheelInput ;
public class WheelTest extends BaseChromeTest {
@Test
public void shouldScrollToElement () {
driver . get ( "https://www.selenium.dev/selenium/web/scrolling_tests/frame_with_nested_scrolling_frame_out_of_view.html" );
WebElement iframe = driver . findElement ( By . tagName ( "iframe" ));
new Actions ( driver )
. scrollToElement ( iframe )
. perform ();
Assertions . assertTrue ( inViewport ( iframe ));
}
@Test
public void shouldScrollFromViewportByGivenAmount () {
driver . get ( "https://www.selenium.dev/selenium/web/scrolling_tests/frame_with_nested_scrolling_frame_out_of_view.html" );
WebElement footer = driver . findElement ( By . tagName ( "footer" ));
int deltaY = footer . getRect (). y ;
new Actions ( driver )
. scrollByAmount ( 0 , deltaY )
. perform ();
Assertions . assertTrue ( inViewport ( footer ));
}
@Test
public void shouldScrollFromElementByGivenAmount () {
driver . get ( "https://www.selenium.dev/selenium/web/scrolling_tests/frame_with_nested_scrolling_frame_out_of_view.html" );
WebElement iframe = driver . findElement ( By . tagName ( "iframe" ));
WheelInput . ScrollOrigin scrollOrigin = WheelInput . ScrollOrigin . fromElement ( iframe );
new Actions ( driver )
. scrollFromOrigin ( scrollOrigin , 0 , 200 )
. perform ();
driver . switchTo (). frame ( iframe );
WebElement checkbox = driver . findElement ( By . name ( "scroll_checkbox" ));
Assertions . assertTrue ( inViewport ( checkbox ));
}
@Test
public void shouldScrollFromElementByGivenAmountWithOffset () {
driver . get ( "https://www.selenium.dev/selenium/web/scrolling_tests/frame_with_nested_scrolling_frame_out_of_view.html" );
WebElement footer = driver . findElement ( By . tagName ( "footer" ));
WheelInput . ScrollOrigin scrollOrigin = WheelInput . ScrollOrigin . fromElement ( footer , 0 , - 50 );
new Actions ( driver )
. scrollFromOrigin ( scrollOrigin , 0 , 200 )
. perform ();
WebElement iframe = driver . findElement ( By . tagName ( "iframe" ));
driver . switchTo (). frame ( iframe );
WebElement checkbox = driver . findElement ( By . name ( "scroll_checkbox" ));
Assertions . assertTrue ( inViewport ( checkbox ));
}
@Test
public void shouldScrollFromViewportByGivenAmountFromOrigin () {
driver . get ( "https://www.selenium.dev/selenium/web/scrolling_tests/frame_with_nested_scrolling_frame.html" );
WheelInput . ScrollOrigin scrollOrigin = WheelInput . ScrollOrigin . fromViewport ( 10 , 10 );
new Actions ( driver )
. scrollFromOrigin ( scrollOrigin , 0 , 200 )
. perform ();
WebElement iframe = driver . findElement ( By . tagName ( "iframe" ));
driver . switchTo (). frame ( iframe );
WebElement checkbox = driver . findElement ( By . name ( "scroll_checkbox" ));
Assertions . assertTrue ( inViewport ( checkbox ));
}
private boolean inViewport ( WebElement element ) {
String script =
"for(var e=arguments[0],f=e.offsetTop,t=e.offsetLeft,o=e.offsetWidth,n=e.offsetHeight;\n"
+ "e.offsetParent;)f+=(e=e.offsetParent).offsetTop,t+=e.offsetLeft;\n"
+ "return f<window.pageYOffset+window.innerHeight&&t<window.pageXOffset+window.innerWidth&&f+n>\n"
+ "window.pageYOffset&&t+o>window.pageXOffset" ;
return ( boolean ) (( JavascriptExecutor ) driver ). executeScript ( script , element );
}
}
iframe = driver . find_element ( By . TAG_NAME , "iframe" )
scroll_origin = ScrollOrigin . from_element ( iframe )
ActionChains ( driver ) \
. scroll_from_origin ( scroll_origin , 0 , 200 ) \
. perform ()
Show full example from time import sleep
from selenium.webdriver import ActionChains
from selenium.webdriver.common.by import By
from selenium.webdriver.common.actions.wheel_input import ScrollOrigin
def test_can_scroll_to_element ( driver ):
driver . get ( "https://selenium.dev/selenium/web/scrolling_tests/frame_with_nested_scrolling_frame_out_of_view.html" )
iframe = driver . find_element ( By . TAG_NAME , "iframe" )
ActionChains ( driver ) \
. scroll_to_element ( iframe ) \
. perform ()
assert _in_viewport ( driver , iframe )
def test_can_scroll_from_viewport_by_amount ( driver ):
driver . get ( "https://selenium.dev/selenium/web/scrolling_tests/frame_with_nested_scrolling_frame_out_of_view.html" )
footer = driver . find_element ( By . TAG_NAME , "footer" )
delta_y = footer . rect [ 'y' ]
ActionChains ( driver ) \
. scroll_by_amount ( 0 , delta_y ) \
. perform ()
sleep ( 0.5 )
assert _in_viewport ( driver , footer )
def test_can_scroll_from_element_by_amount ( driver ):
driver . get ( "https://selenium.dev/selenium/web/scrolling_tests/frame_with_nested_scrolling_frame_out_of_view.html" )
iframe = driver . find_element ( By . TAG_NAME , "iframe" )
scroll_origin = ScrollOrigin . from_element ( iframe )
ActionChains ( driver ) \
. scroll_from_origin ( scroll_origin , 0 , 200 ) \
. perform ()
sleep ( 0.5 )
driver . switch_to . frame ( iframe )
checkbox = driver . find_element ( By . NAME , "scroll_checkbox" )
assert _in_viewport ( driver , checkbox )
def test_can_scroll_from_element_with_offset_by_amount ( driver ):
driver . get ( "https://selenium.dev/selenium/web/scrolling_tests/frame_with_nested_scrolling_frame_out_of_view.html" )
footer = driver . find_element ( By . TAG_NAME , "footer" )
scroll_origin = ScrollOrigin . from_element ( footer , 0 , - 50 )
ActionChains ( driver ) \
. scroll_from_origin ( scroll_origin , 0 , 200 ) \
. perform ()
sleep ( 0.5 )
iframe = driver . find_element ( By . TAG_NAME , "iframe" )
driver . switch_to . frame ( iframe )
checkbox = driver . find_element ( By . NAME , "scroll_checkbox" )
assert _in_viewport ( driver , checkbox )
def test_can_scroll_from_viewport_with_offset_by_amount ( driver ):
driver . get ( "https://selenium.dev/selenium/web/scrolling_tests/frame_with_nested_scrolling_frame.html" )
scroll_origin = ScrollOrigin . from_viewport ( 10 , 10 )
ActionChains ( driver ) \
. scroll_from_origin ( scroll_origin , 0 , 200 ) \
. perform ()
sleep ( 0.5 )
iframe = driver . find_element ( By . TAG_NAME , "iframe" )
driver . switch_to . frame ( iframe )
checkbox = driver . find_element ( By . NAME , "scroll_checkbox" )
assert _in_viewport ( driver , checkbox )
def _in_viewport ( driver , element ):
script = (
"for(var e=arguments[0],f=e.offsetTop,t=e.offsetLeft,o=e.offsetWidth,n=e.offsetHeight; \n "
"e.offsetParent;)f+=(e=e.offsetParent).offsetTop,t+=e.offsetLeft; \n "
"return f<window.pageYOffset+window.innerHeight&&t<window.pageXOffset+window.innerWidth&&f+n> \n "
"window.pageYOffset&&t+o>window.pageXOffset"
)
return driver . execute_script ( script , element )
IWebElement iframe = driver . FindElement ( By . TagName ( "iframe" ));
WheelInputDevice . ScrollOrigin scrollOrigin = new WheelInputDevice . ScrollOrigin
{
Element = iframe
};
new Actions ( driver )
. ScrollFromOrigin ( scrollOrigin , 0 , 200 )
. Perform ();
Show full example using System ;
using Microsoft.VisualStudio.TestTools.UnitTesting ;
using OpenQA.Selenium ;
using OpenQA.Selenium.Interactions ;
namespace SeleniumDocs.ActionsAPI
{
[TestClass]
public class WheelTest : BaseChromeTest
{
[TestMethod]
public void ShouldAllowScrollingToAnElement ()
{
driver . Url =
"https://selenium.dev/selenium/web/scrolling_tests/frame_with_nested_scrolling_frame_out_of_view.html" ;
IWebElement iframe = driver . FindElement ( By . TagName ( "iframe" ));
new Actions ( driver )
. ScrollToElement ( iframe )
. Perform ();
Assert . IsTrue ( IsInViewport ( iframe ));
}
[TestMethod]
public void ShouldAllowScrollingFromViewportByGivenAmount ()
{
driver . Url =
"https://selenium.dev/selenium/web/scrolling_tests/frame_with_nested_scrolling_frame_out_of_view.html" ;
IWebElement footer = driver . FindElement ( By . TagName ( "footer" ));
int deltaY = footer . Location . Y ;
new Actions ( driver )
. ScrollByAmount ( 0 , deltaY )
. Perform ();
Assert . IsTrue ( IsInViewport ( footer ));
}
[TestMethod]
public void ShouldScrollFromElementByGivenAmount ()
{
driver . Url =
"https://selenium.dev/selenium/web/scrolling_tests/frame_with_nested_scrolling_frame_out_of_view.html" ;
IWebElement iframe = driver . FindElement ( By . TagName ( "iframe" ));
WheelInputDevice . ScrollOrigin scrollOrigin = new WheelInputDevice . ScrollOrigin
{
Element = iframe
};
new Actions ( driver )
. ScrollFromOrigin ( scrollOrigin , 0 , 200 )
. Perform ();
driver . SwitchTo (). Frame ( iframe );
IWebElement checkbox = driver . FindElement ( By . Name ( "scroll_checkbox" ));
Assert . IsTrue ( IsInViewport ( checkbox ));
}
[TestMethod]
public void ShouldAllowScrollingFromElementByGivenAmountWithOffset ()
{
driver . Url =
"https://selenium.dev/selenium/web/scrolling_tests/frame_with_nested_scrolling_frame_out_of_view.html" ;
IWebElement footer = driver . FindElement ( By . TagName ( "footer" ));
var scrollOrigin = new WheelInputDevice . ScrollOrigin
{
Element = footer ,
XOffset = 0 ,
YOffset = - 50
};
new Actions ( driver )
. ScrollFromOrigin ( scrollOrigin , 0 , 200 )
. Perform ();
IWebElement iframe = driver . FindElement ( By . TagName ( "iframe" ));
driver . SwitchTo (). Frame ( iframe );
IWebElement checkbox = driver . FindElement ( By . Name ( "scroll_checkbox" ));
Assert . IsTrue ( IsInViewport ( checkbox ));
}
[TestMethod]
public void ShouldAllowScrollingFromViewportByGivenAmountFromOrigin ()
{
driver . Url =
"https://selenium.dev/selenium/web/scrolling_tests/frame_with_nested_scrolling_frame.html" ;
var scrollOrigin = new WheelInputDevice . ScrollOrigin
{
Viewport = true ,
XOffset = 10 ,
YOffset = 10
};
new Actions ( driver )
. ScrollFromOrigin ( scrollOrigin , 0 , 200 )
. Perform ();
IWebElement iframe = driver . FindElement ( By . TagName ( "iframe" ));
driver . SwitchTo (). Frame ( iframe );
IWebElement checkbox = driver . FindElement ( By . Name ( "scroll_checkbox" ));
Assert . IsTrue ( IsInViewport ( checkbox ));
}
private bool IsInViewport ( IWebElement element )
{
String script =
"for(var e=arguments[0],f=e.offsetTop,t=e.offsetLeft,o=e.offsetWidth,n=e.offsetHeight;\n"
+ "e.offsetParent;)f+=(e=e.offsetParent).offsetTop,t+=e.offsetLeft;\n"
+ "return f<window.pageYOffset+window.innerHeight&&t<window.pageXOffset+window.innerWidth&&f+n>\n"
+ "window.pageYOffset&&t+o>window.pageXOffset" ;
IJavaScriptExecutor javascriptDriver = this . driver as IJavaScriptExecutor ;
return ( bool ) javascriptDriver . ExecuteScript ( script , element );
}
}
}
iframe = driver . find_element ( tag_name : 'iframe' )
scroll_origin = Selenium :: WebDriver :: WheelActions :: ScrollOrigin . element ( iframe )
driver . action
. scroll_from ( scroll_origin , 0 , 200 )
. perform
Show full example # frozen_string_literal: true
require 'spec_helper'
RSpec . describe 'Scrolling' do
let ( :driver ) { start_session }
it 'scrolls to element' do
driver . get ( 'https://selenium.dev/selenium/web/scrolling_tests/frame_with_nested_scrolling_frame_out_of_view.html' )
iframe = driver . find_element ( tag_name : 'iframe' )
driver . action
. scroll_to ( iframe )
. perform
expect ( in_viewport? ( iframe )) . to eq true
end
it 'scrolls by given amount' do
driver . get ( 'https://selenium.dev/selenium/web/scrolling_tests/frame_with_nested_scrolling_frame_out_of_view.html' )
footer = driver . find_element ( tag_name : 'footer' )
delta_y = footer . rect . y
driver . action
. scroll_by ( 0 , delta_y )
. perform
expect ( in_viewport? ( footer )) . to eq true
end
it 'scrolls from element by given amount' do
driver . get ( 'https://selenium.dev/selenium/web/scrolling_tests/frame_with_nested_scrolling_frame_out_of_view.html' )
iframe = driver . find_element ( tag_name : 'iframe' )
scroll_origin = Selenium :: WebDriver :: WheelActions :: ScrollOrigin . element ( iframe )
driver . action
. scroll_from ( scroll_origin , 0 , 200 )
. perform
driver . switch_to . frame ( iframe )
checkbox = driver . find_element ( name : 'scroll_checkbox' )
expect ( in_viewport? ( checkbox )) . to eq true
end
it 'scrolls from element by given amount with offset' do
driver . get ( 'https://selenium.dev/selenium/web/scrolling_tests/frame_with_nested_scrolling_frame_out_of_view.html' )
footer = driver . find_element ( tag_name : 'footer' )
scroll_origin = Selenium :: WebDriver :: WheelActions :: ScrollOrigin . element ( footer , 0 , - 50 )
driver . action
. scroll_from ( scroll_origin , 0 , 200 )
. perform
iframe = driver . find_element ( tag_name : 'iframe' )
driver . switch_to . frame ( iframe )
checkbox = driver . find_element ( name : 'scroll_checkbox' )
expect ( in_viewport? ( checkbox )) . to eq true
end
it 'scrolls by given amount with offset' do
driver . get ( 'https://selenium.dev/selenium/web/scrolling_tests/frame_with_nested_scrolling_frame.html' )
scroll_origin = Selenium :: WebDriver :: WheelActions :: ScrollOrigin . viewport ( 10 , 10 )
driver . action
. scroll_from ( scroll_origin , 0 , 200 )
. perform
iframe = driver . find_element ( tag_name : 'iframe' )
driver . switch_to . frame ( iframe )
checkbox = driver . find_element ( name : 'scroll_checkbox' )
expect ( in_viewport? ( checkbox )) . to eq true
end
end
def in_viewport? ( element )
in_viewport = <<~ IN_VIEWPORT
for ( var e = arguments [ 0 ] , f = e . offsetTop , t = e . offsetLeft , o = e . offsetWidth , n = e . offsetHeight ;
e . offsetParent ;) f += ( e = e . offsetParent ) . offsetTop , t += e . offsetLeft ;
return f < window . pageYOffset + window . innerHeight && t < window . pageXOffset + window . innerWidth && f + n >
window . pageYOffset && t + o > window . pageXOffset
IN_VIEWPORT
driver . execute_script ( in_viewport , element )
end
const iframe = await driver . findElement ( By . css ( "iframe" ))
await driver . actions ()
. scroll ( 0 , 0 , 0 , 200 , iframe )
. perform ()
Show full example const { By , Browser , Builder } = require ( 'selenium-webdriver' )
const assert = require ( 'assert' )
describe ( 'Actions API - Wheel Tests' , function () {
let driver
before ( async function () {
driver = await new Builder (). forBrowser ( 'chrome' ). build ();
})
after ( async () => await driver . quit ())
it ( 'Scroll to element' , async function () {
await driver . get ( "https://www.selenium.dev/selenium/web/scrolling_tests/frame_with_nested_scrolling_frame_out_of_view.html" )
const iframe = await driver . findElement ( By . css ( "iframe" ))
await driver . actions ()
. scroll ( 0 , 0 , 0 , 0 , iframe )
. perform ()
assert . ok ( await inViewport ( iframe ))
})
it ( 'Scroll by given amount' , async function () {
await driver . get ( "https://www.selenium.dev/selenium/web/scrolling_tests/frame_with_nested_scrolling_frame_out_of_view.html" )
const footer = await driver . findElement ( By . css ( "footer" ))
const deltaY = ( await footer . getRect ()). y
await driver . actions ()
. scroll ( 0 , 0 , 0 , deltaY )
. perform ()
await driver . sleep ( 500 )
assert . ok ( await inViewport ( footer ))
})
it ( 'Scroll from an element by a given amount' , async function () {
await driver . get ( "https://www.selenium.dev/selenium/web/scrolling_tests/frame_with_nested_scrolling_frame_out_of_view.html" )
const iframe = await driver . findElement ( By . css ( "iframe" ))
await driver . actions ()
. scroll ( 0 , 0 , 0 , 200 , iframe )
. perform ()
await driver . sleep ( 500 )
await driver . switchTo (). frame ( iframe )
const checkbox = await driver . findElement ( By . name ( 'scroll_checkbox' ))
assert . ok ( await inViewport ( checkbox ))
})
it ( 'Scroll from an element with an offset' , async function () {
await driver . get ( "https://www.selenium.dev/selenium/web/scrolling_tests/frame_with_nested_scrolling_frame_out_of_view.html" )
const iframe = await driver . findElement ( By . css ( "iframe" ))
const footer = await driver . findElement ( By . css ( "footer" ))
await driver . actions ()
. scroll ( 0 , - 50 , 0 , 200 , footer )
. perform ()
await driver . sleep ( 500 )
await driver . switchTo (). frame ( iframe )
const checkbox = await driver . findElement ( By . name ( 'scroll_checkbox' ))
assert . ok ( await inViewport ( checkbox ))
})
it ( 'Scroll from an offset of origin (element) by given amount' , async function () {
await driver . get ( "https://www.selenium.dev/selenium/web/scrolling_tests/frame_with_nested_scrolling_frame.html" )
const iframe = await driver . findElement ( By . css ( "iframe" ))
await driver . actions ()
. scroll ( 10 , 10 , 0 , 200 )
. perform ()
await driver . sleep ( 500 )
await driver . switchTo (). frame ( iframe )
const checkbox = await driver . findElement ( By . name ( 'scroll_checkbox' ))
assert . ok ( await inViewport ( checkbox ))
})
function inViewport ( element ) {
return driver . executeScript ( "for(var e=arguments[0],f=e.offsetTop,t=e.offsetLeft,o=e.offsetWidth,n=e.offsetHeight;\ne.offsetParent;)f+=(e=e.offsetParent).offsetTop,t+=e.offsetLeft;\nreturn f<window.pageYOffset+window.innerHeight&&t<window.pageXOffset+window.innerWidth&&f+n>\nwindow.pageYOffset&&t+o>window.pageXOffset" , element )
}
})
val iframe = driver . findElement ( By . tagName ( "iframe" ))
val scrollOrigin = WheelInput . ScrollOrigin . fromElement ( iframe )
Actions ( driver )
. scrollFromOrigin ( scrollOrigin , 0 , 200 )
. perform ()
Show full example 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.JavascriptExecutor
import org.openqa.selenium.WebElement
import org.openqa.selenium.interactions.Actions
import org.openqa.selenium.interactions.WheelInput
class WheelTest : BaseTest () {
@Test
fun shouldScrollToElement () {
driver . get ( "https://www.selenium.dev/selenium/web/scrolling_tests/frame_with_nested_scrolling_frame_out_of_view.html" )
val iframe = driver . findElement ( By . tagName ( "iframe" ))
Actions ( driver )
. scrollToElement ( iframe )
. perform ()
Assertions . assertTrue ( inViewport ( iframe ))
}
@Test
fun shouldScrollFromViewportByGivenAmount () {
driver . get ( "https://www.selenium.dev/selenium/web/scrolling_tests/frame_with_nested_scrolling_frame_out_of_view.html" )
val footer = driver . findElement ( By . tagName ( "footer" ))
val deltaY = footer . getRect (). y
Actions ( driver )
. scrollByAmount ( 0 , deltaY )
. perform ()
Assertions . assertTrue ( inViewport ( footer ))
}
@Test
fun shouldScrollFromElementByGivenAmount () {
driver . get ( "https://www.selenium.dev/selenium/web/scrolling_tests/frame_with_nested_scrolling_frame_out_of_view.html" )
val iframe = driver . findElement ( By . tagName ( "iframe" ))
val scrollOrigin = WheelInput . ScrollOrigin . fromElement ( iframe )
Actions ( driver )
. scrollFromOrigin ( scrollOrigin , 0 , 200 )
. perform ()
driver . switchTo (). frame ( iframe )
val checkbox = driver . findElement ( By . name ( "scroll_checkbox" ))
Assertions . assertTrue ( inViewport ( checkbox ))
}
@Test
fun shouldScrollFromElementByGivenAmountWithOffset () {
driver . get ( "https://www.selenium.dev/selenium/web/scrolling_tests/frame_with_nested_scrolling_frame_out_of_view.html" )
val footer = driver . findElement ( By . tagName ( "footer" ))
val scrollOrigin = WheelInput . ScrollOrigin . fromElement ( footer , 0 , - 50 )
Actions ( driver )
. scrollFromOrigin ( scrollOrigin , 0 , 200 )
. perform ()
val iframe = driver . findElement ( By . tagName ( "iframe" ))
driver . switchTo (). frame ( iframe )
val checkbox = driver . findElement ( By . name ( "scroll_checkbox" ))
Assertions . assertTrue ( inViewport ( checkbox ))
}
@Test
fun shouldScrollFromViewportByGivenAmountFromOrigin () {
driver . get ( "https://www.selenium.dev/selenium/web/scrolling_tests/frame_with_nested_scrolling_frame.html" )
val scrollOrigin = WheelInput . ScrollOrigin . fromViewport ( 10 , 10 )
Actions ( driver )
. scrollFromOrigin ( scrollOrigin , 0 , 200 )
. perform ()
val iframe = driver . findElement ( By . tagName ( "iframe" ))
driver . switchTo (). frame ( iframe )
val checkbox = driver . findElement ( By . name ( "scroll_checkbox" ))
Assertions . assertTrue ( inViewport ( checkbox ))
}
fun inViewport ( element : WebElement ): Boolean {
val script = "for(var e=arguments[0],f=e.offsetTop,t=e.offsetLeft,o=e.offsetWidth,n=e.offsetHeight; \n e.offsetParent;)f+=(e=e.offsetParent).offsetTop,t+=e.offsetLeft; \n return f<window.pageYOffset+window.innerHeight&&t<window.pageXOffset+window.innerWidth&&f+n> \n window.pageYOffset&&t+o>window.pageXOffset"
return ( driver as JavascriptExecutor ). executeScript ( script , element ) as Boolean
}
}
Este cenário é usado quando você precisa rolar apenas uma parte da tela que está fora da janela de visualização ou dentro da janela de visualização, mas a parte da tela que deve ser rolada está a uma distância conhecida de um elemento específico.
Isso utiliza novamente o método “Rolar a Partir”, e além de especificar o elemento, é especificado um deslocamento para indicar o ponto de origem da rolagem. O deslocamento é calculado a partir do centro do elemento fornecido.
Se o elemento estiver fora da janela de visualização, primeiro ele será rolado até a parte inferior da tela. Em seguida, a origem da rolagem será determinada adicionando o deslocamento às coordenadas do centro do elemento, e, finalmente, a página será rolada pelos valores delta x e delta y fornecidos.
Observe que se o deslocamento a partir do centro do elemento estiver fora da janela de visualização, isso resultará em uma exceção.
Java
Python
CSharp
Ruby
JavaScript
Kotlin WebElement footer = driver . findElement ( By . tagName ( "footer" ));
WheelInput . ScrollOrigin scrollOrigin = WheelInput . ScrollOrigin . fromElement ( footer , 0 , - 50 );
new Actions ( driver )
. scrollFromOrigin ( scrollOrigin , 0 , 200 )
. perform ();
Show full example 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.JavascriptExecutor ;
import org.openqa.selenium.WebElement ;
import org.openqa.selenium.interactions.Actions ;
import org.openqa.selenium.interactions.WheelInput ;
public class WheelTest extends BaseChromeTest {
@Test
public void shouldScrollToElement () {
driver . get ( "https://www.selenium.dev/selenium/web/scrolling_tests/frame_with_nested_scrolling_frame_out_of_view.html" );
WebElement iframe = driver . findElement ( By . tagName ( "iframe" ));
new Actions ( driver )
. scrollToElement ( iframe )
. perform ();
Assertions . assertTrue ( inViewport ( iframe ));
}
@Test
public void shouldScrollFromViewportByGivenAmount () {
driver . get ( "https://www.selenium.dev/selenium/web/scrolling_tests/frame_with_nested_scrolling_frame_out_of_view.html" );
WebElement footer = driver . findElement ( By . tagName ( "footer" ));
int deltaY = footer . getRect (). y ;
new Actions ( driver )
. scrollByAmount ( 0 , deltaY )
. perform ();
Assertions . assertTrue ( inViewport ( footer ));
}
@Test
public void shouldScrollFromElementByGivenAmount () {
driver . get ( "https://www.selenium.dev/selenium/web/scrolling_tests/frame_with_nested_scrolling_frame_out_of_view.html" );
WebElement iframe = driver . findElement ( By . tagName ( "iframe" ));
WheelInput . ScrollOrigin scrollOrigin = WheelInput . ScrollOrigin . fromElement ( iframe );
new Actions ( driver )
. scrollFromOrigin ( scrollOrigin , 0 , 200 )
. perform ();
driver . switchTo (). frame ( iframe );
WebElement checkbox = driver . findElement ( By . name ( "scroll_checkbox" ));
Assertions . assertTrue ( inViewport ( checkbox ));
}
@Test
public void shouldScrollFromElementByGivenAmountWithOffset () {
driver . get ( "https://www.selenium.dev/selenium/web/scrolling_tests/frame_with_nested_scrolling_frame_out_of_view.html" );
WebElement footer = driver . findElement ( By . tagName ( "footer" ));
WheelInput . ScrollOrigin scrollOrigin = WheelInput . ScrollOrigin . fromElement ( footer , 0 , - 50 );
new Actions ( driver )
. scrollFromOrigin ( scrollOrigin , 0 , 200 )
. perform ();
WebElement iframe = driver . findElement ( By . tagName ( "iframe" ));
driver . switchTo (). frame ( iframe );
WebElement checkbox = driver . findElement ( By . name ( "scroll_checkbox" ));
Assertions . assertTrue ( inViewport ( checkbox ));
}
@Test
public void shouldScrollFromViewportByGivenAmountFromOrigin () {
driver . get ( "https://www.selenium.dev/selenium/web/scrolling_tests/frame_with_nested_scrolling_frame.html" );
WheelInput . ScrollOrigin scrollOrigin = WheelInput . ScrollOrigin . fromViewport ( 10 , 10 );
new Actions ( driver )
. scrollFromOrigin ( scrollOrigin , 0 , 200 )
. perform ();
WebElement iframe = driver . findElement ( By . tagName ( "iframe" ));
driver . switchTo (). frame ( iframe );
WebElement checkbox = driver . findElement ( By . name ( "scroll_checkbox" ));
Assertions . assertTrue ( inViewport ( checkbox ));
}
private boolean inViewport ( WebElement element ) {
String script =
"for(var e=arguments[0],f=e.offsetTop,t=e.offsetLeft,o=e.offsetWidth,n=e.offsetHeight;\n"
+ "e.offsetParent;)f+=(e=e.offsetParent).offsetTop,t+=e.offsetLeft;\n"
+ "return f<window.pageYOffset+window.innerHeight&&t<window.pageXOffset+window.innerWidth&&f+n>\n"
+ "window.pageYOffset&&t+o>window.pageXOffset" ;
return ( boolean ) (( JavascriptExecutor ) driver ). executeScript ( script , element );
}
}
footer = driver . find_element ( By . TAG_NAME , "footer" )
scroll_origin = ScrollOrigin . from_element ( footer , 0 , - 50 )
ActionChains ( driver ) \
. scroll_from_origin ( scroll_origin , 0 , 200 ) \
. perform ()
Show full example from time import sleep
from selenium.webdriver import ActionChains
from selenium.webdriver.common.by import By
from selenium.webdriver.common.actions.wheel_input import ScrollOrigin
def test_can_scroll_to_element ( driver ):
driver . get ( "https://selenium.dev/selenium/web/scrolling_tests/frame_with_nested_scrolling_frame_out_of_view.html" )
iframe = driver . find_element ( By . TAG_NAME , "iframe" )
ActionChains ( driver ) \
. scroll_to_element ( iframe ) \
. perform ()
assert _in_viewport ( driver , iframe )
def test_can_scroll_from_viewport_by_amount ( driver ):
driver . get ( "https://selenium.dev/selenium/web/scrolling_tests/frame_with_nested_scrolling_frame_out_of_view.html" )
footer = driver . find_element ( By . TAG_NAME , "footer" )
delta_y = footer . rect [ 'y' ]
ActionChains ( driver ) \
. scroll_by_amount ( 0 , delta_y ) \
. perform ()
sleep ( 0.5 )
assert _in_viewport ( driver , footer )
def test_can_scroll_from_element_by_amount ( driver ):
driver . get ( "https://selenium.dev/selenium/web/scrolling_tests/frame_with_nested_scrolling_frame_out_of_view.html" )
iframe = driver . find_element ( By . TAG_NAME , "iframe" )
scroll_origin = ScrollOrigin . from_element ( iframe )
ActionChains ( driver ) \
. scroll_from_origin ( scroll_origin , 0 , 200 ) \
. perform ()
sleep ( 0.5 )
driver . switch_to . frame ( iframe )
checkbox = driver . find_element ( By . NAME , "scroll_checkbox" )
assert _in_viewport ( driver , checkbox )
def test_can_scroll_from_element_with_offset_by_amount ( driver ):
driver . get ( "https://selenium.dev/selenium/web/scrolling_tests/frame_with_nested_scrolling_frame_out_of_view.html" )
footer = driver . find_element ( By . TAG_NAME , "footer" )
scroll_origin = ScrollOrigin . from_element ( footer , 0 , - 50 )
ActionChains ( driver ) \
. scroll_from_origin ( scroll_origin , 0 , 200 ) \
. perform ()
sleep ( 0.5 )
iframe = driver . find_element ( By . TAG_NAME , "iframe" )
driver . switch_to . frame ( iframe )
checkbox = driver . find_element ( By . NAME , "scroll_checkbox" )
assert _in_viewport ( driver , checkbox )
def test_can_scroll_from_viewport_with_offset_by_amount ( driver ):
driver . get ( "https://selenium.dev/selenium/web/scrolling_tests/frame_with_nested_scrolling_frame.html" )
scroll_origin = ScrollOrigin . from_viewport ( 10 , 10 )
ActionChains ( driver ) \
. scroll_from_origin ( scroll_origin , 0 , 200 ) \
. perform ()
sleep ( 0.5 )
iframe = driver . find_element ( By . TAG_NAME , "iframe" )
driver . switch_to . frame ( iframe )
checkbox = driver . find_element ( By . NAME , "scroll_checkbox" )
assert _in_viewport ( driver , checkbox )
def _in_viewport ( driver , element ):
script = (
"for(var e=arguments[0],f=e.offsetTop,t=e.offsetLeft,o=e.offsetWidth,n=e.offsetHeight; \n "
"e.offsetParent;)f+=(e=e.offsetParent).offsetTop,t+=e.offsetLeft; \n "
"return f<window.pageYOffset+window.innerHeight&&t<window.pageXOffset+window.innerWidth&&f+n> \n "
"window.pageYOffset&&t+o>window.pageXOffset"
)
return driver . execute_script ( script , element )
IWebElement footer = driver . FindElement ( By . TagName ( "footer" ));
var scrollOrigin = new WheelInputDevice . ScrollOrigin
{
Element = footer ,
XOffset = 0 ,
YOffset = - 50
};
new Actions ( driver )
. ScrollFromOrigin ( scrollOrigin , 0 , 200 )
. Perform ();
Show full example using System ;
using Microsoft.VisualStudio.TestTools.UnitTesting ;
using OpenQA.Selenium ;
using OpenQA.Selenium.Interactions ;
namespace SeleniumDocs.ActionsAPI
{
[TestClass]
public class WheelTest : BaseChromeTest
{
[TestMethod]
public void ShouldAllowScrollingToAnElement ()
{
driver . Url =
"https://selenium.dev/selenium/web/scrolling_tests/frame_with_nested_scrolling_frame_out_of_view.html" ;
IWebElement iframe = driver . FindElement ( By . TagName ( "iframe" ));
new Actions ( driver )
. ScrollToElement ( iframe )
. Perform ();
Assert . IsTrue ( IsInViewport ( iframe ));
}
[TestMethod]
public void ShouldAllowScrollingFromViewportByGivenAmount ()
{
driver . Url =
"https://selenium.dev/selenium/web/scrolling_tests/frame_with_nested_scrolling_frame_out_of_view.html" ;
IWebElement footer = driver . FindElement ( By . TagName ( "footer" ));
int deltaY = footer . Location . Y ;
new Actions ( driver )
. ScrollByAmount ( 0 , deltaY )
. Perform ();
Assert . IsTrue ( IsInViewport ( footer ));
}
[TestMethod]
public void ShouldScrollFromElementByGivenAmount ()
{
driver . Url =
"https://selenium.dev/selenium/web/scrolling_tests/frame_with_nested_scrolling_frame_out_of_view.html" ;
IWebElement iframe = driver . FindElement ( By . TagName ( "iframe" ));
WheelInputDevice . ScrollOrigin scrollOrigin = new WheelInputDevice . ScrollOrigin
{
Element = iframe
};
new Actions ( driver )
. ScrollFromOrigin ( scrollOrigin , 0 , 200 )
. Perform ();
driver . SwitchTo (). Frame ( iframe );
IWebElement checkbox = driver . FindElement ( By . Name ( "scroll_checkbox" ));
Assert . IsTrue ( IsInViewport ( checkbox ));
}
[TestMethod]
public void ShouldAllowScrollingFromElementByGivenAmountWithOffset ()
{
driver . Url =
"https://selenium.dev/selenium/web/scrolling_tests/frame_with_nested_scrolling_frame_out_of_view.html" ;
IWebElement footer = driver . FindElement ( By . TagName ( "footer" ));
var scrollOrigin = new WheelInputDevice . ScrollOrigin
{
Element = footer ,
XOffset = 0 ,
YOffset = - 50
};
new Actions ( driver )
. ScrollFromOrigin ( scrollOrigin , 0 , 200 )
. Perform ();
IWebElement iframe = driver . FindElement ( By . TagName ( "iframe" ));
driver . SwitchTo (). Frame ( iframe );
IWebElement checkbox = driver . FindElement ( By . Name ( "scroll_checkbox" ));
Assert . IsTrue ( IsInViewport ( checkbox ));
}
[TestMethod]
public void ShouldAllowScrollingFromViewportByGivenAmountFromOrigin ()
{
driver . Url =
"https://selenium.dev/selenium/web/scrolling_tests/frame_with_nested_scrolling_frame.html" ;
var scrollOrigin = new WheelInputDevice . ScrollOrigin
{
Viewport = true ,
XOffset = 10 ,
YOffset = 10
};
new Actions ( driver )
. ScrollFromOrigin ( scrollOrigin , 0 , 200 )
. Perform ();
IWebElement iframe = driver . FindElement ( By . TagName ( "iframe" ));
driver . SwitchTo (). Frame ( iframe );
IWebElement checkbox = driver . FindElement ( By . Name ( "scroll_checkbox" ));
Assert . IsTrue ( IsInViewport ( checkbox ));
}
private bool IsInViewport ( IWebElement element )
{
String script =
"for(var e=arguments[0],f=e.offsetTop,t=e.offsetLeft,o=e.offsetWidth,n=e.offsetHeight;\n"
+ "e.offsetParent;)f+=(e=e.offsetParent).offsetTop,t+=e.offsetLeft;\n"
+ "return f<window.pageYOffset+window.innerHeight&&t<window.pageXOffset+window.innerWidth&&f+n>\n"
+ "window.pageYOffset&&t+o>window.pageXOffset" ;
IJavaScriptExecutor javascriptDriver = this . driver as IJavaScriptExecutor ;
return ( bool ) javascriptDriver . ExecuteScript ( script , element );
}
}
}
footer = driver . find_element ( tag_name : 'footer' )
scroll_origin = Selenium :: WebDriver :: WheelActions :: ScrollOrigin . element ( footer , 0 , - 50 )
driver . action
. scroll_from ( scroll_origin , 0 , 200 )
. perform
Show full example # frozen_string_literal: true
require 'spec_helper'
RSpec . describe 'Scrolling' do
let ( :driver ) { start_session }
it 'scrolls to element' do
driver . get ( 'https://selenium.dev/selenium/web/scrolling_tests/frame_with_nested_scrolling_frame_out_of_view.html' )
iframe = driver . find_element ( tag_name : 'iframe' )
driver . action
. scroll_to ( iframe )
. perform
expect ( in_viewport? ( iframe )) . to eq true
end
it 'scrolls by given amount' do
driver . get ( 'https://selenium.dev/selenium/web/scrolling_tests/frame_with_nested_scrolling_frame_out_of_view.html' )
footer = driver . find_element ( tag_name : 'footer' )
delta_y = footer . rect . y
driver . action
. scroll_by ( 0 , delta_y )
. perform
expect ( in_viewport? ( footer )) . to eq true
end
it 'scrolls from element by given amount' do
driver . get ( 'https://selenium.dev/selenium/web/scrolling_tests/frame_with_nested_scrolling_frame_out_of_view.html' )
iframe = driver . find_element ( tag_name : 'iframe' )
scroll_origin = Selenium :: WebDriver :: WheelActions :: ScrollOrigin . element ( iframe )
driver . action
. scroll_from ( scroll_origin , 0 , 200 )
. perform
driver . switch_to . frame ( iframe )
checkbox = driver . find_element ( name : 'scroll_checkbox' )
expect ( in_viewport? ( checkbox )) . to eq true
end
it 'scrolls from element by given amount with offset' do
driver . get ( 'https://selenium.dev/selenium/web/scrolling_tests/frame_with_nested_scrolling_frame_out_of_view.html' )
footer = driver . find_element ( tag_name : 'footer' )
scroll_origin = Selenium :: WebDriver :: WheelActions :: ScrollOrigin . element ( footer , 0 , - 50 )
driver . action
. scroll_from ( scroll_origin , 0 , 200 )
. perform
iframe = driver . find_element ( tag_name : 'iframe' )
driver . switch_to . frame ( iframe )
checkbox = driver . find_element ( name : 'scroll_checkbox' )
expect ( in_viewport? ( checkbox )) . to eq true
end
it 'scrolls by given amount with offset' do
driver . get ( 'https://selenium.dev/selenium/web/scrolling_tests/frame_with_nested_scrolling_frame.html' )
scroll_origin = Selenium :: WebDriver :: WheelActions :: ScrollOrigin . viewport ( 10 , 10 )
driver . action
. scroll_from ( scroll_origin , 0 , 200 )
. perform
iframe = driver . find_element ( tag_name : 'iframe' )
driver . switch_to . frame ( iframe )
checkbox = driver . find_element ( name : 'scroll_checkbox' )
expect ( in_viewport? ( checkbox )) . to eq true
end
end
def in_viewport? ( element )
in_viewport = <<~ IN_VIEWPORT
for ( var e = arguments [ 0 ] , f = e . offsetTop , t = e . offsetLeft , o = e . offsetWidth , n = e . offsetHeight ;
e . offsetParent ;) f += ( e = e . offsetParent ) . offsetTop , t += e . offsetLeft ;
return f < window . pageYOffset + window . innerHeight && t < window . pageXOffset + window . innerWidth && f + n >
window . pageYOffset && t + o > window . pageXOffset
IN_VIEWPORT
driver . execute_script ( in_viewport , element )
end
const footer = await driver . findElement ( By . css ( "footer" ))
await driver . actions ()
. scroll ( 0 , - 50 , 0 , 200 , footer )
. perform ()
Show full example const { By , Browser , Builder } = require ( 'selenium-webdriver' )
const assert = require ( 'assert' )
describe ( 'Actions API - Wheel Tests' , function () {
let driver
before ( async function () {
driver = await new Builder (). forBrowser ( 'chrome' ). build ();
})
after ( async () => await driver . quit ())
it ( 'Scroll to element' , async function () {
await driver . get ( "https://www.selenium.dev/selenium/web/scrolling_tests/frame_with_nested_scrolling_frame_out_of_view.html" )
const iframe = await driver . findElement ( By . css ( "iframe" ))
await driver . actions ()
. scroll ( 0 , 0 , 0 , 0 , iframe )
. perform ()
assert . ok ( await inViewport ( iframe ))
})
it ( 'Scroll by given amount' , async function () {
await driver . get ( "https://www.selenium.dev/selenium/web/scrolling_tests/frame_with_nested_scrolling_frame_out_of_view.html" )
const footer = await driver . findElement ( By . css ( "footer" ))
const deltaY = ( await footer . getRect ()). y
await driver . actions ()
. scroll ( 0 , 0 , 0 , deltaY )
. perform ()
await driver . sleep ( 500 )
assert . ok ( await inViewport ( footer ))
})
it ( 'Scroll from an element by a given amount' , async function () {
await driver . get ( "https://www.selenium.dev/selenium/web/scrolling_tests/frame_with_nested_scrolling_frame_out_of_view.html" )
const iframe = await driver . findElement ( By . css ( "iframe" ))
await driver . actions ()
. scroll ( 0 , 0 , 0 , 200 , iframe )
. perform ()
await driver . sleep ( 500 )
await driver . switchTo (). frame ( iframe )
const checkbox = await driver . findElement ( By . name ( 'scroll_checkbox' ))
assert . ok ( await inViewport ( checkbox ))
})
it ( 'Scroll from an element with an offset' , async function () {
await driver . get ( "https://www.selenium.dev/selenium/web/scrolling_tests/frame_with_nested_scrolling_frame_out_of_view.html" )
const iframe = await driver . findElement ( By . css ( "iframe" ))
const footer = await driver . findElement ( By . css ( "footer" ))
await driver . actions ()
. scroll ( 0 , - 50 , 0 , 200 , footer )
. perform ()
await driver . sleep ( 500 )
await driver . switchTo (). frame ( iframe )
const checkbox = await driver . findElement ( By . name ( 'scroll_checkbox' ))
assert . ok ( await inViewport ( checkbox ))
})
it ( 'Scroll from an offset of origin (element) by given amount' , async function () {
await driver . get ( "https://www.selenium.dev/selenium/web/scrolling_tests/frame_with_nested_scrolling_frame.html" )
const iframe = await driver . findElement ( By . css ( "iframe" ))
await driver . actions ()
. scroll ( 10 , 10 , 0 , 200 )
. perform ()
await driver . sleep ( 500 )
await driver . switchTo (). frame ( iframe )
const checkbox = await driver . findElement ( By . name ( 'scroll_checkbox' ))
assert . ok ( await inViewport ( checkbox ))
})
function inViewport ( element ) {
return driver . executeScript ( "for(var e=arguments[0],f=e.offsetTop,t=e.offsetLeft,o=e.offsetWidth,n=e.offsetHeight;\ne.offsetParent;)f+=(e=e.offsetParent).offsetTop,t+=e.offsetLeft;\nreturn f<window.pageYOffset+window.innerHeight&&t<window.pageXOffset+window.innerWidth&&f+n>\nwindow.pageYOffset&&t+o>window.pageXOffset" , element )
}
})
val footer = driver . findElement ( By . tagName ( "footer" ))
val scrollOrigin = WheelInput . ScrollOrigin . fromElement ( footer , 0 , - 50 )
Actions ( driver )
. scrollFromOrigin ( scrollOrigin , 0 , 200 )
. perform ()
Show full example 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.JavascriptExecutor
import org.openqa.selenium.WebElement
import org.openqa.selenium.interactions.Actions
import org.openqa.selenium.interactions.WheelInput
class WheelTest : BaseTest () {
@Test
fun shouldScrollToElement () {
driver . get ( "https://www.selenium.dev/selenium/web/scrolling_tests/frame_with_nested_scrolling_frame_out_of_view.html" )
val iframe = driver . findElement ( By . tagName ( "iframe" ))
Actions ( driver )
. scrollToElement ( iframe )
. perform ()
Assertions . assertTrue ( inViewport ( iframe ))
}
@Test
fun shouldScrollFromViewportByGivenAmount () {
driver . get ( "https://www.selenium.dev/selenium/web/scrolling_tests/frame_with_nested_scrolling_frame_out_of_view.html" )
val footer = driver . findElement ( By . tagName ( "footer" ))
val deltaY = footer . getRect (). y
Actions ( driver )
. scrollByAmount ( 0 , deltaY )
. perform ()
Assertions . assertTrue ( inViewport ( footer ))
}
@Test
fun shouldScrollFromElementByGivenAmount () {
driver . get ( "https://www.selenium.dev/selenium/web/scrolling_tests/frame_with_nested_scrolling_frame_out_of_view.html" )
val iframe = driver . findElement ( By . tagName ( "iframe" ))
val scrollOrigin = WheelInput . ScrollOrigin . fromElement ( iframe )
Actions ( driver )
. scrollFromOrigin ( scrollOrigin , 0 , 200 )
. perform ()
driver . switchTo (). frame ( iframe )
val checkbox = driver . findElement ( By . name ( "scroll_checkbox" ))
Assertions . assertTrue ( inViewport ( checkbox ))
}
@Test
fun shouldScrollFromElementByGivenAmountWithOffset () {
driver . get ( "https://www.selenium.dev/selenium/web/scrolling_tests/frame_with_nested_scrolling_frame_out_of_view.html" )
val footer = driver . findElement ( By . tagName ( "footer" ))
val scrollOrigin = WheelInput . ScrollOrigin . fromElement ( footer , 0 , - 50 )
Actions ( driver )
. scrollFromOrigin ( scrollOrigin , 0 , 200 )
. perform ()
val iframe = driver . findElement ( By . tagName ( "iframe" ))
driver . switchTo (). frame ( iframe )
val checkbox = driver . findElement ( By . name ( "scroll_checkbox" ))
Assertions . assertTrue ( inViewport ( checkbox ))
}
@Test
fun shouldScrollFromViewportByGivenAmountFromOrigin () {
driver . get ( "https://www.selenium.dev/selenium/web/scrolling_tests/frame_with_nested_scrolling_frame.html" )
val scrollOrigin = WheelInput . ScrollOrigin . fromViewport ( 10 , 10 )
Actions ( driver )
. scrollFromOrigin ( scrollOrigin , 0 , 200 )
. perform ()
val iframe = driver . findElement ( By . tagName ( "iframe" ))
driver . switchTo (). frame ( iframe )
val checkbox = driver . findElement ( By . name ( "scroll_checkbox" ))
Assertions . assertTrue ( inViewport ( checkbox ))
}
fun inViewport ( element : WebElement ): Boolean {
val script = "for(var e=arguments[0],f=e.offsetTop,t=e.offsetLeft,o=e.offsetWidth,n=e.offsetHeight; \n e.offsetParent;)f+=(e=e.offsetParent).offsetTop,t+=e.offsetLeft; \n return f<window.pageYOffset+window.innerHeight&&t<window.pageXOffset+window.innerWidth&&f+n> \n window.pageYOffset&&t+o>window.pageXOffset"
return ( driver as JavascriptExecutor ). executeScript ( script , element ) as Boolean
}
}
Rolar a partir de um Deslocamento de Origem (Elemento) por uma Quantidade Especificada O cenário final é usado quando você precisa rolar apenas uma parte da tela que já está dentro da janela de visualização.
Isso utiliza novamente o método “Rolar a Partir”, mas a janela de visualização é designada em vez de um elemento. Um deslocamento é especificado a partir do canto superior esquerdo da janela de visualização atual. Após determinar o ponto de origem, a página será rolada pelos valores delta x e delta y fornecidos.
Observe que se o deslocamento a partir do canto superior esquerdo da janela de visualização sair da tela, isso resultará em uma exceção.
Java
Python
CSharp
Ruby
JavaScript
Kotlin WheelInput . ScrollOrigin scrollOrigin = WheelInput . ScrollOrigin . fromViewport ( 10 , 10 );
new Actions ( driver )
. scrollFromOrigin ( scrollOrigin , 0 , 200 )
. perform ();
Show full example 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.JavascriptExecutor ;
import org.openqa.selenium.WebElement ;
import org.openqa.selenium.interactions.Actions ;
import org.openqa.selenium.interactions.WheelInput ;
public class WheelTest extends BaseChromeTest {
@Test
public void shouldScrollToElement () {
driver . get ( "https://www.selenium.dev/selenium/web/scrolling_tests/frame_with_nested_scrolling_frame_out_of_view.html" );
WebElement iframe = driver . findElement ( By . tagName ( "iframe" ));
new Actions ( driver )
. scrollToElement ( iframe )
. perform ();
Assertions . assertTrue ( inViewport ( iframe ));
}
@Test
public void shouldScrollFromViewportByGivenAmount () {
driver . get ( "https://www.selenium.dev/selenium/web/scrolling_tests/frame_with_nested_scrolling_frame_out_of_view.html" );
WebElement footer = driver . findElement ( By . tagName ( "footer" ));
int deltaY = footer . getRect (). y ;
new Actions ( driver )
. scrollByAmount ( 0 , deltaY )
. perform ();
Assertions . assertTrue ( inViewport ( footer ));
}
@Test
public void shouldScrollFromElementByGivenAmount () {
driver . get ( "https://www.selenium.dev/selenium/web/scrolling_tests/frame_with_nested_scrolling_frame_out_of_view.html" );
WebElement iframe = driver . findElement ( By . tagName ( "iframe" ));
WheelInput . ScrollOrigin scrollOrigin = WheelInput . ScrollOrigin . fromElement ( iframe );
new Actions ( driver )
. scrollFromOrigin ( scrollOrigin , 0 , 200 )
. perform ();
driver . switchTo (). frame ( iframe );
WebElement checkbox = driver . findElement ( By . name ( "scroll_checkbox" ));
Assertions . assertTrue ( inViewport ( checkbox ));
}
@Test
public void shouldScrollFromElementByGivenAmountWithOffset () {
driver . get ( "https://www.selenium.dev/selenium/web/scrolling_tests/frame_with_nested_scrolling_frame_out_of_view.html" );
WebElement footer = driver . findElement ( By . tagName ( "footer" ));
WheelInput . ScrollOrigin scrollOrigin = WheelInput . ScrollOrigin . fromElement ( footer , 0 , - 50 );
new Actions ( driver )
. scrollFromOrigin ( scrollOrigin , 0 , 200 )
. perform ();
WebElement iframe = driver . findElement ( By . tagName ( "iframe" ));
driver . switchTo (). frame ( iframe );
WebElement checkbox = driver . findElement ( By . name ( "scroll_checkbox" ));
Assertions . assertTrue ( inViewport ( checkbox ));
}
@Test
public void shouldScrollFromViewportByGivenAmountFromOrigin () {
driver . get ( "https://www.selenium.dev/selenium/web/scrolling_tests/frame_with_nested_scrolling_frame.html" );
WheelInput . ScrollOrigin scrollOrigin = WheelInput . ScrollOrigin . fromViewport ( 10 , 10 );
new Actions ( driver )
. scrollFromOrigin ( scrollOrigin , 0 , 200 )
. perform ();
WebElement iframe = driver . findElement ( By . tagName ( "iframe" ));
driver . switchTo (). frame ( iframe );
WebElement checkbox = driver . findElement ( By . name ( "scroll_checkbox" ));
Assertions . assertTrue ( inViewport ( checkbox ));
}
private boolean inViewport ( WebElement element ) {
String script =
"for(var e=arguments[0],f=e.offsetTop,t=e.offsetLeft,o=e.offsetWidth,n=e.offsetHeight;\n"
+ "e.offsetParent;)f+=(e=e.offsetParent).offsetTop,t+=e.offsetLeft;\n"
+ "return f<window.pageYOffset+window.innerHeight&&t<window.pageXOffset+window.innerWidth&&f+n>\n"
+ "window.pageYOffset&&t+o>window.pageXOffset" ;
return ( boolean ) (( JavascriptExecutor ) driver ). executeScript ( script , element );
}
}
scroll_origin = ScrollOrigin . from_viewport ( 10 , 10 )
ActionChains ( driver ) \
. scroll_from_origin ( scroll_origin , 0 , 200 ) \
. perform ()
Show full example from time import sleep
from selenium.webdriver import ActionChains
from selenium.webdriver.common.by import By
from selenium.webdriver.common.actions.wheel_input import ScrollOrigin
def test_can_scroll_to_element ( driver ):
driver . get ( "https://selenium.dev/selenium/web/scrolling_tests/frame_with_nested_scrolling_frame_out_of_view.html" )
iframe = driver . find_element ( By . TAG_NAME , "iframe" )
ActionChains ( driver ) \
. scroll_to_element ( iframe ) \
. perform ()
assert _in_viewport ( driver , iframe )
def test_can_scroll_from_viewport_by_amount ( driver ):
driver . get ( "https://selenium.dev/selenium/web/scrolling_tests/frame_with_nested_scrolling_frame_out_of_view.html" )
footer = driver . find_element ( By . TAG_NAME , "footer" )
delta_y = footer . rect [ 'y' ]
ActionChains ( driver ) \
. scroll_by_amount ( 0 , delta_y ) \
. perform ()
sleep ( 0.5 )
assert _in_viewport ( driver , footer )
def test_can_scroll_from_element_by_amount ( driver ):
driver . get ( "https://selenium.dev/selenium/web/scrolling_tests/frame_with_nested_scrolling_frame_out_of_view.html" )
iframe = driver . find_element ( By . TAG_NAME , "iframe" )
scroll_origin = ScrollOrigin . from_element ( iframe )
ActionChains ( driver ) \
. scroll_from_origin ( scroll_origin , 0 , 200 ) \
. perform ()
sleep ( 0.5 )
driver . switch_to . frame ( iframe )
checkbox = driver . find_element ( By . NAME , "scroll_checkbox" )
assert _in_viewport ( driver , checkbox )
def test_can_scroll_from_element_with_offset_by_amount ( driver ):
driver . get ( "https://selenium.dev/selenium/web/scrolling_tests/frame_with_nested_scrolling_frame_out_of_view.html" )
footer = driver . find_element ( By . TAG_NAME , "footer" )
scroll_origin = ScrollOrigin . from_element ( footer , 0 , - 50 )
ActionChains ( driver ) \
. scroll_from_origin ( scroll_origin , 0 , 200 ) \
. perform ()
sleep ( 0.5 )
iframe = driver . find_element ( By . TAG_NAME , "iframe" )
driver . switch_to . frame ( iframe )
checkbox = driver . find_element ( By . NAME , "scroll_checkbox" )
assert _in_viewport ( driver , checkbox )
def test_can_scroll_from_viewport_with_offset_by_amount ( driver ):
driver . get ( "https://selenium.dev/selenium/web/scrolling_tests/frame_with_nested_scrolling_frame.html" )
scroll_origin = ScrollOrigin . from_viewport ( 10 , 10 )
ActionChains ( driver ) \
. scroll_from_origin ( scroll_origin , 0 , 200 ) \
. perform ()
sleep ( 0.5 )
iframe = driver . find_element ( By . TAG_NAME , "iframe" )
driver . switch_to . frame ( iframe )
checkbox = driver . find_element ( By . NAME , "scroll_checkbox" )
assert _in_viewport ( driver , checkbox )
def _in_viewport ( driver , element ):
script = (
"for(var e=arguments[0],f=e.offsetTop,t=e.offsetLeft,o=e.offsetWidth,n=e.offsetHeight; \n "
"e.offsetParent;)f+=(e=e.offsetParent).offsetTop,t+=e.offsetLeft; \n "
"return f<window.pageYOffset+window.innerHeight&&t<window.pageXOffset+window.innerWidth&&f+n> \n "
"window.pageYOffset&&t+o>window.pageXOffset"
)
return driver . execute_script ( script , element )
var scrollOrigin = new WheelInputDevice . ScrollOrigin
{
Viewport = true ,
XOffset = 10 ,
YOffset = 10
};
new Actions ( driver )
. ScrollFromOrigin ( scrollOrigin , 0 , 200 )
. Perform ();
Show full example using System ;
using Microsoft.VisualStudio.TestTools.UnitTesting ;
using OpenQA.Selenium ;
using OpenQA.Selenium.Interactions ;
namespace SeleniumDocs.ActionsAPI
{
[TestClass]
public class WheelTest : BaseChromeTest
{
[TestMethod]
public void ShouldAllowScrollingToAnElement ()
{
driver . Url =
"https://selenium.dev/selenium/web/scrolling_tests/frame_with_nested_scrolling_frame_out_of_view.html" ;
IWebElement iframe = driver . FindElement ( By . TagName ( "iframe" ));
new Actions ( driver )
. ScrollToElement ( iframe )
. Perform ();
Assert . IsTrue ( IsInViewport ( iframe ));
}
[TestMethod]
public void ShouldAllowScrollingFromViewportByGivenAmount ()
{
driver . Url =
"https://selenium.dev/selenium/web/scrolling_tests/frame_with_nested_scrolling_frame_out_of_view.html" ;
IWebElement footer = driver . FindElement ( By . TagName ( "footer" ));
int deltaY = footer . Location . Y ;
new Actions ( driver )
. ScrollByAmount ( 0 , deltaY )
. Perform ();
Assert . IsTrue ( IsInViewport ( footer ));
}
[TestMethod]
public void ShouldScrollFromElementByGivenAmount ()
{
driver . Url =
"https://selenium.dev/selenium/web/scrolling_tests/frame_with_nested_scrolling_frame_out_of_view.html" ;
IWebElement iframe = driver . FindElement ( By . TagName ( "iframe" ));
WheelInputDevice . ScrollOrigin scrollOrigin = new WheelInputDevice . ScrollOrigin
{
Element = iframe
};
new Actions ( driver )
. ScrollFromOrigin ( scrollOrigin , 0 , 200 )
. Perform ();
driver . SwitchTo (). Frame ( iframe );
IWebElement checkbox = driver . FindElement ( By . Name ( "scroll_checkbox" ));
Assert . IsTrue ( IsInViewport ( checkbox ));
}
[TestMethod]
public void ShouldAllowScrollingFromElementByGivenAmountWithOffset ()
{
driver . Url =
"https://selenium.dev/selenium/web/scrolling_tests/frame_with_nested_scrolling_frame_out_of_view.html" ;
IWebElement footer = driver . FindElement ( By . TagName ( "footer" ));
var scrollOrigin = new WheelInputDevice . ScrollOrigin
{
Element = footer ,
XOffset = 0 ,
YOffset = - 50
};
new Actions ( driver )
. ScrollFromOrigin ( scrollOrigin , 0 , 200 )
. Perform ();
IWebElement iframe = driver . FindElement ( By . TagName ( "iframe" ));
driver . SwitchTo (). Frame ( iframe );
IWebElement checkbox = driver . FindElement ( By . Name ( "scroll_checkbox" ));
Assert . IsTrue ( IsInViewport ( checkbox ));
}
[TestMethod]
public void ShouldAllowScrollingFromViewportByGivenAmountFromOrigin ()
{
driver . Url =
"https://selenium.dev/selenium/web/scrolling_tests/frame_with_nested_scrolling_frame.html" ;
var scrollOrigin = new WheelInputDevice . ScrollOrigin
{
Viewport = true ,
XOffset = 10 ,
YOffset = 10
};
new Actions ( driver )
. ScrollFromOrigin ( scrollOrigin , 0 , 200 )
. Perform ();
IWebElement iframe = driver . FindElement ( By . TagName ( "iframe" ));
driver . SwitchTo (). Frame ( iframe );
IWebElement checkbox = driver . FindElement ( By . Name ( "scroll_checkbox" ));
Assert . IsTrue ( IsInViewport ( checkbox ));
}
private bool IsInViewport ( IWebElement element )
{
String script =
"for(var e=arguments[0],f=e.offsetTop,t=e.offsetLeft,o=e.offsetWidth,n=e.offsetHeight;\n"
+ "e.offsetParent;)f+=(e=e.offsetParent).offsetTop,t+=e.offsetLeft;\n"
+ "return f<window.pageYOffset+window.innerHeight&&t<window.pageXOffset+window.innerWidth&&f+n>\n"
+ "window.pageYOffset&&t+o>window.pageXOffset" ;
IJavaScriptExecutor javascriptDriver = this . driver as IJavaScriptExecutor ;
return ( bool ) javascriptDriver . ExecuteScript ( script , element );
}
}
}
scroll_origin = Selenium :: WebDriver :: WheelActions :: ScrollOrigin . viewport ( 10 , 10 )
driver . action
. scroll_from ( scroll_origin , 0 , 200 )
. perform
Show full example # frozen_string_literal: true
require 'spec_helper'
RSpec . describe 'Scrolling' do
let ( :driver ) { start_session }
it 'scrolls to element' do
driver . get ( 'https://selenium.dev/selenium/web/scrolling_tests/frame_with_nested_scrolling_frame_out_of_view.html' )
iframe = driver . find_element ( tag_name : 'iframe' )
driver . action
. scroll_to ( iframe )
. perform
expect ( in_viewport? ( iframe )) . to eq true
end
it 'scrolls by given amount' do
driver . get ( 'https://selenium.dev/selenium/web/scrolling_tests/frame_with_nested_scrolling_frame_out_of_view.html' )
footer = driver . find_element ( tag_name : 'footer' )
delta_y = footer . rect . y
driver . action
. scroll_by ( 0 , delta_y )
. perform
expect ( in_viewport? ( footer )) . to eq true
end
it 'scrolls from element by given amount' do
driver . get ( 'https://selenium.dev/selenium/web/scrolling_tests/frame_with_nested_scrolling_frame_out_of_view.html' )
iframe = driver . find_element ( tag_name : 'iframe' )
scroll_origin = Selenium :: WebDriver :: WheelActions :: ScrollOrigin . element ( iframe )
driver . action
. scroll_from ( scroll_origin , 0 , 200 )
. perform
driver . switch_to . frame ( iframe )
checkbox = driver . find_element ( name : 'scroll_checkbox' )
expect ( in_viewport? ( checkbox )) . to eq true
end
it 'scrolls from element by given amount with offset' do
driver . get ( 'https://selenium.dev/selenium/web/scrolling_tests/frame_with_nested_scrolling_frame_out_of_view.html' )
footer = driver . find_element ( tag_name : 'footer' )
scroll_origin = Selenium :: WebDriver :: WheelActions :: ScrollOrigin . element ( footer , 0 , - 50 )
driver . action
. scroll_from ( scroll_origin , 0 , 200 )
. perform
iframe = driver . find_element ( tag_name : 'iframe' )
driver . switch_to . frame ( iframe )
checkbox = driver . find_element ( name : 'scroll_checkbox' )
expect ( in_viewport? ( checkbox )) . to eq true
end
it 'scrolls by given amount with offset' do
driver . get ( 'https://selenium.dev/selenium/web/scrolling_tests/frame_with_nested_scrolling_frame.html' )
scroll_origin = Selenium :: WebDriver :: WheelActions :: ScrollOrigin . viewport ( 10 , 10 )
driver . action
. scroll_from ( scroll_origin , 0 , 200 )
. perform
iframe = driver . find_element ( tag_name : 'iframe' )
driver . switch_to . frame ( iframe )
checkbox = driver . find_element ( name : 'scroll_checkbox' )
expect ( in_viewport? ( checkbox )) . to eq true
end
end
def in_viewport? ( element )
in_viewport = <<~ IN_VIEWPORT
for ( var e = arguments [ 0 ] , f = e . offsetTop , t = e . offsetLeft , o = e . offsetWidth , n = e . offsetHeight ;
e . offsetParent ;) f += ( e = e . offsetParent ) . offsetTop , t += e . offsetLeft ;
return f < window . pageYOffset + window . innerHeight && t < window . pageXOffset + window . innerWidth && f + n >
window . pageYOffset && t + o > window . pageXOffset
IN_VIEWPORT
driver . execute_script ( in_viewport , element )
end
await driver . actions ()
. scroll ( 10 , 10 , 0 , 200 )
. perform ()
Show full example const { By , Browser , Builder } = require ( 'selenium-webdriver' )
const assert = require ( 'assert' )
describe ( 'Actions API - Wheel Tests' , function () {
let driver
before ( async function () {
driver = await new Builder (). forBrowser ( 'chrome' ). build ();
})
after ( async () => await driver . quit ())
it ( 'Scroll to element' , async function () {
await driver . get ( "https://www.selenium.dev/selenium/web/scrolling_tests/frame_with_nested_scrolling_frame_out_of_view.html" )
const iframe = await driver . findElement ( By . css ( "iframe" ))
await driver . actions ()
. scroll ( 0 , 0 , 0 , 0 , iframe )
. perform ()
assert . ok ( await inViewport ( iframe ))
})
it ( 'Scroll by given amount' , async function () {
await driver . get ( "https://www.selenium.dev/selenium/web/scrolling_tests/frame_with_nested_scrolling_frame_out_of_view.html" )
const footer = await driver . findElement ( By . css ( "footer" ))
const deltaY = ( await footer . getRect ()). y
await driver . actions ()
. scroll ( 0 , 0 , 0 , deltaY )
. perform ()
await driver . sleep ( 500 )
assert . ok ( await inViewport ( footer ))
})
it ( 'Scroll from an element by a given amount' , async function () {
await driver . get ( "https://www.selenium.dev/selenium/web/scrolling_tests/frame_with_nested_scrolling_frame_out_of_view.html" )
const iframe = await driver . findElement ( By . css ( "iframe" ))
await driver . actions ()
. scroll ( 0 , 0 , 0 , 200 , iframe )
. perform ()
await driver . sleep ( 500 )
await driver . switchTo (). frame ( iframe )
const checkbox = await driver . findElement ( By . name ( 'scroll_checkbox' ))
assert . ok ( await inViewport ( checkbox ))
})
it ( 'Scroll from an element with an offset' , async function () {
await driver . get ( "https://www.selenium.dev/selenium/web/scrolling_tests/frame_with_nested_scrolling_frame_out_of_view.html" )
const iframe = await driver . findElement ( By . css ( "iframe" ))
const footer = await driver . findElement ( By . css ( "footer" ))
await driver . actions ()
. scroll ( 0 , - 50 , 0 , 200 , footer )
. perform ()
await driver . sleep ( 500 )
await driver . switchTo (). frame ( iframe )
const checkbox = await driver . findElement ( By . name ( 'scroll_checkbox' ))
assert . ok ( await inViewport ( checkbox ))
})
it ( 'Scroll from an offset of origin (element) by given amount' , async function () {
await driver . get ( "https://www.selenium.dev/selenium/web/scrolling_tests/frame_with_nested_scrolling_frame.html" )
const iframe = await driver . findElement ( By . css ( "iframe" ))
await driver . actions ()
. scroll ( 10 , 10 , 0 , 200 )
. perform ()
await driver . sleep ( 500 )
await driver . switchTo (). frame ( iframe )
const checkbox = await driver . findElement ( By . name ( 'scroll_checkbox' ))
assert . ok ( await inViewport ( checkbox ))
})
function inViewport ( element ) {
return driver . executeScript ( "for(var e=arguments[0],f=e.offsetTop,t=e.offsetLeft,o=e.offsetWidth,n=e.offsetHeight;\ne.offsetParent;)f+=(e=e.offsetParent).offsetTop,t+=e.offsetLeft;\nreturn f<window.pageYOffset+window.innerHeight&&t<window.pageXOffset+window.innerWidth&&f+n>\nwindow.pageYOffset&&t+o>window.pageXOffset" , element )
}
})
val scrollOrigin = WheelInput . ScrollOrigin . fromViewport ( 10 , 10 )
Actions ( driver )
. scrollFromOrigin ( scrollOrigin , 0 , 200 )
. perform ()
Show full example 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.JavascriptExecutor
import org.openqa.selenium.WebElement
import org.openqa.selenium.interactions.Actions
import org.openqa.selenium.interactions.WheelInput
class WheelTest : BaseTest () {
@Test
fun shouldScrollToElement () {
driver . get ( "https://www.selenium.dev/selenium/web/scrolling_tests/frame_with_nested_scrolling_frame_out_of_view.html" )
val iframe = driver . findElement ( By . tagName ( "iframe" ))
Actions ( driver )
. scrollToElement ( iframe )
. perform ()
Assertions . assertTrue ( inViewport ( iframe ))
}
@Test
fun shouldScrollFromViewportByGivenAmount () {
driver . get ( "https://www.selenium.dev/selenium/web/scrolling_tests/frame_with_nested_scrolling_frame_out_of_view.html" )
val footer = driver . findElement ( By . tagName ( "footer" ))
val deltaY = footer . getRect (). y
Actions ( driver )
. scrollByAmount ( 0 , deltaY )
. perform ()
Assertions . assertTrue ( inViewport ( footer ))
}
@Test
fun shouldScrollFromElementByGivenAmount () {
driver . get ( "https://www.selenium.dev/selenium/web/scrolling_tests/frame_with_nested_scrolling_frame_out_of_view.html" )
val iframe = driver . findElement ( By . tagName ( "iframe" ))
val scrollOrigin = WheelInput . ScrollOrigin . fromElement ( iframe )
Actions ( driver )
. scrollFromOrigin ( scrollOrigin , 0 , 200 )
. perform ()
driver . switchTo (). frame ( iframe )
val checkbox = driver . findElement ( By . name ( "scroll_checkbox" ))
Assertions . assertTrue ( inViewport ( checkbox ))
}
@Test
fun shouldScrollFromElementByGivenAmountWithOffset () {
driver . get ( "https://www.selenium.dev/selenium/web/scrolling_tests/frame_with_nested_scrolling_frame_out_of_view.html" )
val footer = driver . findElement ( By . tagName ( "footer" ))
val scrollOrigin = WheelInput . ScrollOrigin . fromElement ( footer , 0 , - 50 )
Actions ( driver )
. scrollFromOrigin ( scrollOrigin , 0 , 200 )
. perform ()
val iframe = driver . findElement ( By . tagName ( "iframe" ))
driver . switchTo (). frame ( iframe )
val checkbox = driver . findElement ( By . name ( "scroll_checkbox" ))
Assertions . assertTrue ( inViewport ( checkbox ))
}
@Test
fun shouldScrollFromViewportByGivenAmountFromOrigin () {
driver . get ( "https://www.selenium.dev/selenium/web/scrolling_tests/frame_with_nested_scrolling_frame.html" )
val scrollOrigin = WheelInput . ScrollOrigin . fromViewport ( 10 , 10 )
Actions ( driver )
. scrollFromOrigin ( scrollOrigin , 0 , 200 )
. perform ()
val iframe = driver . findElement ( By . tagName ( "iframe" ))
driver . switchTo (). frame ( iframe )
val checkbox = driver . findElement ( By . name ( "scroll_checkbox" ))
Assertions . assertTrue ( inViewport ( checkbox ))
}
fun inViewport ( element : WebElement ): Boolean {
val script = "for(var e=arguments[0],f=e.offsetTop,t=e.offsetLeft,o=e.offsetWidth,n=e.offsetHeight; \n e.offsetParent;)f+=(e=e.offsetParent).offsetTop,t+=e.offsetLeft; \n return f<window.pageYOffset+window.innerHeight&&t<window.pageXOffset+window.innerWidth&&f+n> \n window.pageYOffset&&t+o>window.pageXOffset"
return ( driver as JavascriptExecutor ). executeScript ( script , element ) as Boolean
}
}