packagedev.selenium.interactions;importdev.selenium.BaseChromeTest;importorg.junit.jupiter.api.Assertions;importorg.junit.jupiter.api.Test;importorg.openqa.selenium.Cookie;importjava.util.Set;publicclassInteractionsTestextendsBaseChromeTest{@TestpublicvoidgetTitle(){try{
driver.get("https://www.selenium.dev/");// get titleString title = driver.getTitle();Assertions.assertEquals(title,"Selenium");}finally{
driver.quit();}}@TestpublicvoidgetCurrentUrl(){try{
driver.get("https://www.selenium.dev/");// get current urlString url = driver.getCurrentUrl();Assertions.assertEquals(url,"https://www.selenium.dev/");}finally{
driver.quit();}}}
// Licensed to the Software Freedom Conservancy (SFC) under one// or more contributor license agreements. See the NOTICE file// distributed with this work for additional information// regarding copyright ownership. The SFC licenses this file// to you under the Apache License, Version 2.0 (the// "License"); you may not use this file except in compliance// with the License. You may obtain a copy of the License at//// http://www.apache.org/licenses/LICENSE-2.0//// Unless required by applicable law or agreed to in writing,// software distributed under the License is distributed on an// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY// KIND, either express or implied. See the License for the// specific language governing permissions and limitations// under the License.usingSystem;usingMicrosoft.VisualStudio.TestTools.UnitTesting;usingOpenQA.Selenium;usingOpenQA.Selenium.Chrome;namespaceSeleniumDocumentation.SeleniumInteractions{[TestClass]publicclassInteractionsTest{[TestMethod]publicvoidTestInteractions(){WebDriver driver =newChromeDriver();
driver.Manage().Timeouts().ImplicitWait = TimeSpan.FromMilliseconds(500);// Navigate to Url
driver.Url="https://www.selenium.dev/";//GetTitleString title = driver.Title;
Assert.AreEqual(title,"Selenium");//GetCurrentURLString url = driver.Url;
Assert.AreEqual(url,"https://www.selenium.dev/");//quitting driver
driver.Quit();//close all windows}}}
const{Builder }=require('selenium-webdriver');const assert =require("node:assert");describe('Interactions',function(){let driver;before(asyncfunction(){
driver =newBuilder().forBrowser('chrome').build();});after(async()=>await driver.quit());it('Should be able to get title and current url',asyncfunction(){const url ='https://www.selenium.dev/';await driver.get(url);//Get Current titlelet title =await driver.getTitle();
assert.equal(title,"Selenium");//Get Current urllet currentUrl =await driver.getCurrentUrl();
assert.equal(currentUrl, url);});});
driver.title
Coletar a URL atual
Você pode ler a URL atual na barra de endereço do navegador usando:
packagedev.selenium.interactions;importdev.selenium.BaseChromeTest;importorg.junit.jupiter.api.Assertions;importorg.junit.jupiter.api.Test;importorg.openqa.selenium.Cookie;importjava.util.Set;publicclassInteractionsTestextendsBaseChromeTest{@TestpublicvoidgetTitle(){try{
driver.get("https://www.selenium.dev/");// get titleString title = driver.getTitle();Assertions.assertEquals(title,"Selenium");}finally{
driver.quit();}}@TestpublicvoidgetCurrentUrl(){try{
driver.get("https://www.selenium.dev/");// get current urlString url = driver.getCurrentUrl();Assertions.assertEquals(url,"https://www.selenium.dev/");}finally{
driver.quit();}}}
// Licensed to the Software Freedom Conservancy (SFC) under one// or more contributor license agreements. See the NOTICE file// distributed with this work for additional information// regarding copyright ownership. The SFC licenses this file// to you under the Apache License, Version 2.0 (the// "License"); you may not use this file except in compliance// with the License. You may obtain a copy of the License at//// http://www.apache.org/licenses/LICENSE-2.0//// Unless required by applicable law or agreed to in writing,// software distributed under the License is distributed on an// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY// KIND, either express or implied. See the License for the// specific language governing permissions and limitations// under the License.usingSystem;usingMicrosoft.VisualStudio.TestTools.UnitTesting;usingOpenQA.Selenium;usingOpenQA.Selenium.Chrome;namespaceSeleniumDocumentation.SeleniumInteractions{[TestClass]publicclassInteractionsTest{[TestMethod]publicvoidTestInteractions(){WebDriver driver =newChromeDriver();
driver.Manage().Timeouts().ImplicitWait = TimeSpan.FromMilliseconds(500);// Navigate to Url
driver.Url="https://www.selenium.dev/";//GetTitleString title = driver.Title;
Assert.AreEqual(title,"Selenium");//GetCurrentURLString url = driver.Url;
Assert.AreEqual(url,"https://www.selenium.dev/");//quitting driver
driver.Quit();//close all windows}}}
const{Builder }=require('selenium-webdriver');const assert =require("node:assert");describe('Interactions',function(){let driver;before(asyncfunction(){
driver =newBuilder().forBrowser('chrome').build();});after(async()=>await driver.quit());it('Should be able to get title and current url',asyncfunction(){const url ='https://www.selenium.dev/';await driver.get(url);//Get Current titlelet title =await driver.getTitle();
assert.equal(title,"Selenium");//Get Current urllet currentUrl =await driver.getCurrentUrl();
assert.equal(currentUrl, url);});});
driver.currentUrl
1 - Browser navigation
Navegar para
A primeira coisa que você vai querer fazer depois de iniciar um navegador é
abrir o seu site. Isso pode ser feito em uma única linha, utilize o seguinte comando:
//Convenient
driver.get("https://selenium.dev");//Longer way
driver.navigate().to("https://selenium.dev");
packagedev.selenium.interactions;importorg.junit.jupiter.api.Test;importorg.openqa.selenium.WebDriver;importorg.openqa.selenium.chrome.ChromeDriver;importstaticorg.junit.jupiter.api.Assertions.assertEquals;publicclassNavigationTest{@TestpublicvoidnavigateBrowser(){WebDriver driver =newChromeDriver();//Convenient
driver.get("https://selenium.dev");//Longer way
driver.navigate().to("https://selenium.dev");String title = driver.getTitle();assertEquals(title,"Selenium");//Back
driver.navigate().back();
title = driver.getTitle();assertEquals(title,"Selenium");//Forward
driver.navigate().forward();
title = driver.getTitle();assertEquals(title,"Selenium");//Refresh
driver.navigate().refresh();
title = driver.getTitle();assertEquals(title,"Selenium");
driver.quit();}}
from selenium import webdriver
driver = webdriver.Chrome()
driver.get("https://www.selenium.dev")
driver.get("https://www.selenium.dev/selenium/web/index.html")
title = driver.title
assert title =="Index of Available Pages"
driver.back()
title = driver.title
assert title =="Selenium"
driver.forward()
title = driver.title
assert title =="Index of Available Pages"
driver.refresh()
title = driver.title
assert title =="Index of Available Pages"
driver.quit()
const{Builder }=require('selenium-webdriver');const assert =require("node:assert");describe('Interactions - Navigation',function(){let driver;before(asyncfunction(){
driver =newBuilder().forBrowser('chrome').build();});after(async()=>await driver.quit());it('Browser navigation test',asyncfunction(){//Convenientawait driver.get('https://www.selenium.dev');//Longer wayawait driver.navigate().to("https://www.selenium.dev/selenium/web/index.html");let title =await driver.getTitle();
assert.equal(title,"Index of Available Pages");//Backawait driver.navigate().back();
title =await driver.getTitle();
assert.equal(title,"Selenium");//Forwardawait driver.navigate().forward();
title =await driver.getTitle();
assert.equal(title,"Index of Available Pages");//Refreshawait driver.navigate().refresh();
title =await driver.getTitle();
assert.equal(title,"Index of Available Pages");});});
//Convenient
driver.get("https://selenium.dev")//Longer way
driver.navigate().to("https://selenium.dev")
packagedev.selenium.interactions;importorg.junit.jupiter.api.Test;importorg.openqa.selenium.WebDriver;importorg.openqa.selenium.chrome.ChromeDriver;importstaticorg.junit.jupiter.api.Assertions.assertEquals;publicclassNavigationTest{@TestpublicvoidnavigateBrowser(){WebDriver driver =newChromeDriver();//Convenient
driver.get("https://selenium.dev");//Longer way
driver.navigate().to("https://selenium.dev");String title = driver.getTitle();assertEquals(title,"Selenium");//Back
driver.navigate().back();
title = driver.getTitle();assertEquals(title,"Selenium");//Forward
driver.navigate().forward();
title = driver.getTitle();assertEquals(title,"Selenium");//Refresh
driver.navigate().refresh();
title = driver.getTitle();assertEquals(title,"Selenium");
driver.quit();}}
from selenium import webdriver
driver = webdriver.Chrome()
driver.get("https://www.selenium.dev")
driver.get("https://www.selenium.dev/selenium/web/index.html")
title = driver.title
assert title =="Index of Available Pages"
driver.back()
title = driver.title
assert title =="Selenium"
driver.forward()
title = driver.title
assert title =="Index of Available Pages"
driver.refresh()
title = driver.title
assert title =="Index of Available Pages"
driver.quit()
const{Builder }=require('selenium-webdriver');const assert =require("node:assert");describe('Interactions - Navigation',function(){let driver;before(asyncfunction(){
driver =newBuilder().forBrowser('chrome').build();});after(async()=>await driver.quit());it('Browser navigation test',asyncfunction(){//Convenientawait driver.get('https://www.selenium.dev');//Longer wayawait driver.navigate().to("https://www.selenium.dev/selenium/web/index.html");let title =await driver.getTitle();
assert.equal(title,"Index of Available Pages");//Backawait driver.navigate().back();
title =await driver.getTitle();
assert.equal(title,"Selenium");//Forwardawait driver.navigate().forward();
title =await driver.getTitle();
assert.equal(title,"Index of Available Pages");//Refreshawait driver.navigate().refresh();
title =await driver.getTitle();
assert.equal(title,"Index of Available Pages");});});
packagedev.selenium.interactions;importorg.junit.jupiter.api.Test;importorg.openqa.selenium.WebDriver;importorg.openqa.selenium.chrome.ChromeDriver;importstaticorg.junit.jupiter.api.Assertions.assertEquals;publicclassNavigationTest{@TestpublicvoidnavigateBrowser(){WebDriver driver =newChromeDriver();//Convenient
driver.get("https://selenium.dev");//Longer way
driver.navigate().to("https://selenium.dev");String title = driver.getTitle();assertEquals(title,"Selenium");//Back
driver.navigate().back();
title = driver.getTitle();assertEquals(title,"Selenium");//Forward
driver.navigate().forward();
title = driver.getTitle();assertEquals(title,"Selenium");//Refresh
driver.navigate().refresh();
title = driver.getTitle();assertEquals(title,"Selenium");
driver.quit();}}
from selenium import webdriver
driver = webdriver.Chrome()
driver.get("https://www.selenium.dev")
driver.get("https://www.selenium.dev/selenium/web/index.html")
title = driver.title
assert title =="Index of Available Pages"
driver.back()
title = driver.title
assert title =="Selenium"
driver.forward()
title = driver.title
assert title =="Index of Available Pages"
driver.refresh()
title = driver.title
assert title =="Index of Available Pages"
driver.quit()
const{Builder }=require('selenium-webdriver');const assert =require("node:assert");describe('Interactions - Navigation',function(){let driver;before(asyncfunction(){
driver =newBuilder().forBrowser('chrome').build();});after(async()=>await driver.quit());it('Browser navigation test',asyncfunction(){//Convenientawait driver.get('https://www.selenium.dev');//Longer wayawait driver.navigate().to("https://www.selenium.dev/selenium/web/index.html");let title =await driver.getTitle();
assert.equal(title,"Index of Available Pages");//Backawait driver.navigate().back();
title =await driver.getTitle();
assert.equal(title,"Selenium");//Forwardawait driver.navigate().forward();
title =await driver.getTitle();
assert.equal(title,"Index of Available Pages");//Refreshawait driver.navigate().refresh();
title =await driver.getTitle();
assert.equal(title,"Index of Available Pages");});});
packagedev.selenium.interactions;importorg.junit.jupiter.api.Test;importorg.openqa.selenium.WebDriver;importorg.openqa.selenium.chrome.ChromeDriver;importstaticorg.junit.jupiter.api.Assertions.assertEquals;publicclassNavigationTest{@TestpublicvoidnavigateBrowser(){WebDriver driver =newChromeDriver();//Convenient
driver.get("https://selenium.dev");//Longer way
driver.navigate().to("https://selenium.dev");String title = driver.getTitle();assertEquals(title,"Selenium");//Back
driver.navigate().back();
title = driver.getTitle();assertEquals(title,"Selenium");//Forward
driver.navigate().forward();
title = driver.getTitle();assertEquals(title,"Selenium");//Refresh
driver.navigate().refresh();
title = driver.getTitle();assertEquals(title,"Selenium");
driver.quit();}}
from selenium import webdriver
driver = webdriver.Chrome()
driver.get("https://www.selenium.dev")
driver.get("https://www.selenium.dev/selenium/web/index.html")
title = driver.title
assert title =="Index of Available Pages"
driver.back()
title = driver.title
assert title =="Selenium"
driver.forward()
title = driver.title
assert title =="Index of Available Pages"
driver.refresh()
title = driver.title
assert title =="Index of Available Pages"
driver.quit()
const{Builder }=require('selenium-webdriver');const assert =require("node:assert");describe('Interactions - Navigation',function(){let driver;before(asyncfunction(){
driver =newBuilder().forBrowser('chrome').build();});after(async()=>await driver.quit());it('Browser navigation test',asyncfunction(){//Convenientawait driver.get('https://www.selenium.dev');//Longer wayawait driver.navigate().to("https://www.selenium.dev/selenium/web/index.html");let title =await driver.getTitle();
assert.equal(title,"Index of Available Pages");//Backawait driver.navigate().back();
title =await driver.getTitle();
assert.equal(title,"Selenium");//Forwardawait driver.navigate().forward();
title =await driver.getTitle();
assert.equal(title,"Index of Available Pages");//Refreshawait driver.navigate().refresh();
title =await driver.getTitle();
assert.equal(title,"Index of Available Pages");});});
driver.navigate().refresh()
2 - Alertas, prompts e confirmações JavaScript
WebDriver fornece uma API para trabalhar com os três tipos nativos de
mensagens pop-up oferecidas pelo JavaScript. Esses pop-ups são estilizados pelo
navegador e oferecem personalização limitada.
Alertas
O mais simples deles é referido como um alerta, que mostra um
mensagem personalizada e um único botão que dispensa o alerta, rotulado
na maioria dos navegadores como OK. Ele também pode ser dispensado na maioria dos navegadores
pressionando o botão Fechar, mas isso sempre fará a mesma coisa que
o botão OK. Veja um exemplo de alerta .
O WebDriver pode obter o texto do pop-up e aceitar ou dispensar esses
alertas.
//Click the link to activate the alertJavascriptExecutor js =(JavascriptExecutor) driver;//execute js for alert
js.executeScript("alert('Sample Alert');");WebDriverWait wait =newWebDriverWait(driver,Duration.ofSeconds(30));
// Licensed to the Software Freedom Conservancy (SFC) under one// or more contributor license agreements. See the NOTICE file// distributed with this work for additional information// regarding copyright ownership. The SFC licenses this file// to you under the Apache License, Version 2.0 (the// "License"); you may not use this file except in compliance// with the License. You may obtain a copy of the License at//// http://www.apache.org/licenses/LICENSE-2.0//// Unless required by applicable law or agreed to in writing,// software distributed under the License is distributed on an// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY// KIND, either express or implied. See the License for the// specific language governing permissions and limitations// under the License.importdev.selenium.BaseTest;importorg.junit.jupiter.api.Test;importorg.openqa.selenium.*;importorg.openqa.selenium.chrome.ChromeDriver;importorg.openqa.selenium.chrome.ChromeOptions;importorg.openqa.selenium.support.ui.ExpectedConditions;importorg.openqa.selenium.support.ui.WebDriverWait;importjava.time.Duration;importstaticorg.junit.jupiter.api.Assertions.assertEquals;publicclassAlertsTestextendsBaseTest{@TestpublicvoidtestForAlerts()throwsException{ChromeOptions chromeOptions =getDefaultChromeOptions();
chromeOptions.addArguments("disable-search-engine-choice-screen");WebDriver driver =newChromeDriver(chromeOptions);
driver.manage().timeouts().implicitlyWait(Duration.ofMillis(500));
driver.manage().window().maximize();//Navigate to Url
driver.get("https://www.selenium.dev/documentation/webdriver/interactions/alerts/");//Simple Alert//Click the link to activate the alertJavascriptExecutor js =(JavascriptExecutor) driver;//execute js for alert
js.executeScript("alert('Sample Alert');");WebDriverWait wait =newWebDriverWait(driver,Duration.ofSeconds(30));//Wait for the alert to be displayed and store it in a variable
wait.until(ExpectedConditions.alertIsPresent());Alert alert = driver.switchTo().alert();//Store the alert text in a variable and verify itString text = alert.getText();assertEquals(text,"Sample Alert");//Press the OK button
alert.accept();//Confirm//execute js for confirm
js.executeScript("confirm('Are you sure?');");//Wait for the alert to be displayed
wait =newWebDriverWait(driver,Duration.ofSeconds(30));
wait.until(ExpectedConditions.alertIsPresent());
alert = driver.switchTo().alert();//Store the alert text in a variable and verify it
text = alert.getText();assertEquals(text,"Are you sure?");//Press the Cancel button
alert.dismiss();//Prompt//execute js for prompt
js.executeScript("prompt('What is your name?');");//Wait for the alert to be displayed and store it in a variable
wait =newWebDriverWait(driver,Duration.ofSeconds(30));
wait.until(ExpectedConditions.alertIsPresent());
alert = driver.switchTo().alert();//Store the alert text in a variable and verify it
text = alert.getText();assertEquals(text,"What is your name?");//Type your message
alert.sendKeys("Selenium");//Press the OK button
alert.accept();//quit the browser
driver.quit();}}
element = driver.find_element(By.LINK_TEXT,"See an example alert")
element.click()
wait = WebDriverWait(driver, timeout=2)
alert = wait.until(lambda d : d.switch_to.alert)
text = alert.text
alert.accept()
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
global url
url ="https://www.selenium.dev/documentation/webdriver/interactions/alerts/"deftest_alert_popup():
driver = webdriver.Chrome()
driver.get(url)
element = driver.find_element(By.LINK_TEXT,"See an example alert")
element.click()
wait = WebDriverWait(driver, timeout=2)
alert = wait.until(lambda d : d.switch_to.alert)
text = alert.text
alert.accept()assert text =="Sample alert"
driver.quit()deftest_confirm_popup():
driver = webdriver.Chrome()
driver.get(url)
element = driver.find_element(By.LINK_TEXT,"See a sample confirm")
driver.execute_script("arguments[0].click();", element)
wait = WebDriverWait(driver, timeout=2)
alert = wait.until(lambda d : d.switch_to.alert)
text = alert.text
alert.dismiss()assert text =="Are you sure?"
driver.quit()deftest_prompt_popup():
driver = webdriver.Chrome()
driver.get(url)
element = driver.find_element(By.LINK_TEXT,"See a sample prompt")
driver.execute_script("arguments[0].click();", element)
wait = WebDriverWait(driver, timeout=2)
alert = wait.until(lambda d : d.switch_to.alert)
alert.send_keys("Selenium")
text = alert.text
alert.accept()assert text =="What is your tool of choice?"
driver.quit()
# Store the alert reference in a variable
alert = driver.switch_to.alert
# Get the text of the alert
alert.text
# Press on Cancel button
alert.dismiss
# frozen_string_literal: truerequire'spec_helper'RSpec.describe 'Alerts'do
let(:driver){ start_session }
before do
driver.navigate.to 'https://selenium.dev'end
it 'interacts with an alert'do
driver.execute_script 'alert("Hello, World!")'# Store the alert reference in a variable
alert = driver.switch_to.alert
# Get the text of the alert
alert.text
# Press on Cancel button
alert.dismiss
end
it 'interacts with a confirm'do
driver.execute_script 'confirm("Are you sure?")'# Store the alert reference in a variable
alert = driver.switch_to.alert
# Get the text of the alert
alert.text
# Press on Cancel button
alert.dismiss
end
it 'interacts with a prompt'do
driver.execute_script 'prompt("What is your name?")'# Store the alert reference in a variable
alert = driver.switch_to.alert
# Type a message
alert.send_keys('selenium')# Press on Ok button
alert.accept
endend
let alert =await driver.switchTo().alert();let alertText =await alert.getText();await alert.accept();
const{ By, Builder, until }=require('selenium-webdriver');const assert =require("node:assert");describe('Interactions - Alerts',function(){let driver;before(asyncfunction(){
driver =awaitnewBuilder().forBrowser('chrome').build();});after(async()=>await driver.quit());it('Should be able to getText from alert and accept',asyncfunction(){await driver.get('https://www.selenium.dev/selenium/web/alerts.html');await driver.findElement(By.id("alert")).click();await driver.wait(until.alertIsPresent());let alert =await driver.switchTo().alert();let alertText =await alert.getText();await alert.accept();// Verify
assert.equal(alertText,"cheese");});it('Should be able to getText from alert and dismiss',asyncfunction(){await driver.get('https://www.selenium.dev/selenium/web/alerts.html');await driver.findElement(By.id("confirm")).click();await driver.wait(until.alertIsPresent());let alert =await driver.switchTo().alert();let alertText =await alert.getText();await alert.dismiss();// Verify
assert.equal(alertText,"Are you sure?");});it('Should be able to enter text in alert prompt',asyncfunction(){let text ='Selenium';await driver.get('https://www.selenium.dev/selenium/web/alerts.html');await driver.findElement(By.id("prompt")).click();await driver.wait(until.alertIsPresent());let alert =await driver.switchTo().alert();//Type your messageawait alert.sendKeys(text);await alert.accept();let enteredText =await driver.findElement(By.id('text'));
assert.equal(await enteredText.getText(), text);});});
//Click the link to activate the alert
driver.findElement(By.linkText("See an example alert")).click()//Wait for the alert to be displayed and store it in a variableval alert = wait.until(ExpectedConditions.alertIsPresent())//Store the alert text in a variableval text = alert.getText()//Press the OK button
alert.accept()
Confirmação
Uma caixa de confirmação é semelhante a um alerta, exceto que o usuário também pode escolher
cancelar a mensagem. Veja
uma amostra de confirmação .
Este exemplo também mostra uma abordagem diferente para armazenar um alerta:
String text = alert.getText();assertEquals(text,"Sample Alert");//Press the OK button
// Licensed to the Software Freedom Conservancy (SFC) under one// or more contributor license agreements. See the NOTICE file// distributed with this work for additional information// regarding copyright ownership. The SFC licenses this file// to you under the Apache License, Version 2.0 (the// "License"); you may not use this file except in compliance// with the License. You may obtain a copy of the License at//// http://www.apache.org/licenses/LICENSE-2.0//// Unless required by applicable law or agreed to in writing,// software distributed under the License is distributed on an// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY// KIND, either express or implied. See the License for the// specific language governing permissions and limitations// under the License.importdev.selenium.BaseTest;importorg.junit.jupiter.api.Test;importorg.openqa.selenium.*;importorg.openqa.selenium.chrome.ChromeDriver;importorg.openqa.selenium.chrome.ChromeOptions;importorg.openqa.selenium.support.ui.ExpectedConditions;importorg.openqa.selenium.support.ui.WebDriverWait;importjava.time.Duration;importstaticorg.junit.jupiter.api.Assertions.assertEquals;publicclassAlertsTestextendsBaseTest{@TestpublicvoidtestForAlerts()throwsException{ChromeOptions chromeOptions =getDefaultChromeOptions();
chromeOptions.addArguments("disable-search-engine-choice-screen");WebDriver driver =newChromeDriver(chromeOptions);
driver.manage().timeouts().implicitlyWait(Duration.ofMillis(500));
driver.manage().window().maximize();//Navigate to Url
driver.get("https://www.selenium.dev/documentation/webdriver/interactions/alerts/");//Simple Alert//Click the link to activate the alertJavascriptExecutor js =(JavascriptExecutor) driver;//execute js for alert
js.executeScript("alert('Sample Alert');");WebDriverWait wait =newWebDriverWait(driver,Duration.ofSeconds(30));//Wait for the alert to be displayed and store it in a variable
wait.until(ExpectedConditions.alertIsPresent());Alert alert = driver.switchTo().alert();//Store the alert text in a variable and verify itString text = alert.getText();assertEquals(text,"Sample Alert");//Press the OK button
alert.accept();//Confirm//execute js for confirm
js.executeScript("confirm('Are you sure?');");//Wait for the alert to be displayed
wait =newWebDriverWait(driver,Duration.ofSeconds(30));
wait.until(ExpectedConditions.alertIsPresent());
alert = driver.switchTo().alert();//Store the alert text in a variable and verify it
text = alert.getText();assertEquals(text,"Are you sure?");//Press the Cancel button
alert.dismiss();//Prompt//execute js for prompt
js.executeScript("prompt('What is your name?');");//Wait for the alert to be displayed and store it in a variable
wait =newWebDriverWait(driver,Duration.ofSeconds(30));
wait.until(ExpectedConditions.alertIsPresent());
alert = driver.switchTo().alert();//Store the alert text in a variable and verify it
text = alert.getText();assertEquals(text,"What is your name?");//Type your message
alert.sendKeys("Selenium");//Press the OK button
alert.accept();//quit the browser
driver.quit();}}
element = driver.find_element(By.LINK_TEXT,"See a sample confirm")
driver.execute_script("arguments[0].click();", element)
wait = WebDriverWait(driver, timeout=2)
alert = wait.until(lambda d : d.switch_to.alert)
text = alert.text
alert.dismiss()
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
global url
url ="https://www.selenium.dev/documentation/webdriver/interactions/alerts/"deftest_alert_popup():
driver = webdriver.Chrome()
driver.get(url)
element = driver.find_element(By.LINK_TEXT,"See an example alert")
element.click()
wait = WebDriverWait(driver, timeout=2)
alert = wait.until(lambda d : d.switch_to.alert)
text = alert.text
alert.accept()assert text =="Sample alert"
driver.quit()deftest_confirm_popup():
driver = webdriver.Chrome()
driver.get(url)
element = driver.find_element(By.LINK_TEXT,"See a sample confirm")
driver.execute_script("arguments[0].click();", element)
wait = WebDriverWait(driver, timeout=2)
alert = wait.until(lambda d : d.switch_to.alert)
text = alert.text
alert.dismiss()assert text =="Are you sure?"
driver.quit()deftest_prompt_popup():
driver = webdriver.Chrome()
driver.get(url)
element = driver.find_element(By.LINK_TEXT,"See a sample prompt")
driver.execute_script("arguments[0].click();", element)
wait = WebDriverWait(driver, timeout=2)
alert = wait.until(lambda d : d.switch_to.alert)
alert.send_keys("Selenium")
text = alert.text
alert.accept()assert text =="What is your tool of choice?"
driver.quit()
//Click the link to activate the alert
driver.FindElement(By.LinkText("See a sample confirm")).Click();//Wait for the alert to be displayed
wait.Until(ExpectedConditions.AlertIsPresent());//Store the alert in a variableIAlert alert = driver.SwitchTo().Alert();//Store the alert in a variable for reusestring text = alert.Text;//Press the Cancel button
alert.Dismiss();
# Store the alert reference in a variable
alert = driver.switch_to.alert
# Get the text of the alert
alert.text
# Press on Cancel button
alert.dismiss
# frozen_string_literal: truerequire'spec_helper'RSpec.describe 'Alerts'do
let(:driver){ start_session }
before do
driver.navigate.to 'https://selenium.dev'end
it 'interacts with an alert'do
driver.execute_script 'alert("Hello, World!")'# Store the alert reference in a variable
alert = driver.switch_to.alert
# Get the text of the alert
alert.text
# Press on Cancel button
alert.dismiss
end
it 'interacts with a confirm'do
driver.execute_script 'confirm("Are you sure?")'# Store the alert reference in a variable
alert = driver.switch_to.alert
# Get the text of the alert
alert.text
# Press on Cancel button
alert.dismiss
end
it 'interacts with a prompt'do
driver.execute_script 'prompt("What is your name?")'# Store the alert reference in a variable
alert = driver.switch_to.alert
# Type a message
alert.send_keys('selenium')# Press on Ok button
alert.accept
endend
let alert =await driver.switchTo().alert();let alertText =await alert.getText();await alert.dismiss();
const{ By, Builder, until }=require('selenium-webdriver');const assert =require("node:assert");describe('Interactions - Alerts',function(){let driver;before(asyncfunction(){
driver =awaitnewBuilder().forBrowser('chrome').build();});after(async()=>await driver.quit());it('Should be able to getText from alert and accept',asyncfunction(){await driver.get('https://www.selenium.dev/selenium/web/alerts.html');await driver.findElement(By.id("alert")).click();await driver.wait(until.alertIsPresent());let alert =await driver.switchTo().alert();let alertText =await alert.getText();await alert.accept();// Verify
assert.equal(alertText,"cheese");});it('Should be able to getText from alert and dismiss',asyncfunction(){await driver.get('https://www.selenium.dev/selenium/web/alerts.html');await driver.findElement(By.id("confirm")).click();await driver.wait(until.alertIsPresent());let alert =await driver.switchTo().alert();let alertText =await alert.getText();await alert.dismiss();// Verify
assert.equal(alertText,"Are you sure?");});it('Should be able to enter text in alert prompt',asyncfunction(){let text ='Selenium';await driver.get('https://www.selenium.dev/selenium/web/alerts.html');await driver.findElement(By.id("prompt")).click();await driver.wait(until.alertIsPresent());let alert =await driver.switchTo().alert();//Type your messageawait alert.sendKeys(text);await alert.accept();let enteredText =await driver.findElement(By.id('text'));
assert.equal(await enteredText.getText(), text);});});
//Click the link to activate the alert
driver.findElement(By.linkText("See a sample confirm")).click()//Wait for the alert to be displayed
wait.until(ExpectedConditions.alertIsPresent())//Store the alert in a variableval alert = driver.switchTo().alert()//Store the alert in a variable for reuseval text = alert.text
//Press the Cancel button
alert.dismiss()
Prompt
Os prompts são semelhantes às caixas de confirmação, exceto que também incluem um texto de
entrada. Semelhante a trabalhar com elementos de formulário, você pode
usar o sendKeys do WebDriver para preencher uma resposta. Isso substituirá
completamente o espaço de texto de exemplo. Pressionar o botão Cancelar não enviará nenhum texto.
Veja um exemplo de prompt .
js.executeScript("confirm('Are you sure?');");//Wait for the alert to be displayed
wait =newWebDriverWait(driver,Duration.ofSeconds(30));
wait.until(ExpectedConditions.alertIsPresent());
// Licensed to the Software Freedom Conservancy (SFC) under one// or more contributor license agreements. See the NOTICE file// distributed with this work for additional information// regarding copyright ownership. The SFC licenses this file// to you under the Apache License, Version 2.0 (the// "License"); you may not use this file except in compliance// with the License. You may obtain a copy of the License at//// http://www.apache.org/licenses/LICENSE-2.0//// Unless required by applicable law or agreed to in writing,// software distributed under the License is distributed on an// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY// KIND, either express or implied. See the License for the// specific language governing permissions and limitations// under the License.importdev.selenium.BaseTest;importorg.junit.jupiter.api.Test;importorg.openqa.selenium.*;importorg.openqa.selenium.chrome.ChromeDriver;importorg.openqa.selenium.chrome.ChromeOptions;importorg.openqa.selenium.support.ui.ExpectedConditions;importorg.openqa.selenium.support.ui.WebDriverWait;importjava.time.Duration;importstaticorg.junit.jupiter.api.Assertions.assertEquals;publicclassAlertsTestextendsBaseTest{@TestpublicvoidtestForAlerts()throwsException{ChromeOptions chromeOptions =getDefaultChromeOptions();
chromeOptions.addArguments("disable-search-engine-choice-screen");WebDriver driver =newChromeDriver(chromeOptions);
driver.manage().timeouts().implicitlyWait(Duration.ofMillis(500));
driver.manage().window().maximize();//Navigate to Url
driver.get("https://www.selenium.dev/documentation/webdriver/interactions/alerts/");//Simple Alert//Click the link to activate the alertJavascriptExecutor js =(JavascriptExecutor) driver;//execute js for alert
js.executeScript("alert('Sample Alert');");WebDriverWait wait =newWebDriverWait(driver,Duration.ofSeconds(30));//Wait for the alert to be displayed and store it in a variable
wait.until(ExpectedConditions.alertIsPresent());Alert alert = driver.switchTo().alert();//Store the alert text in a variable and verify itString text = alert.getText();assertEquals(text,"Sample Alert");//Press the OK button
alert.accept();//Confirm//execute js for confirm
js.executeScript("confirm('Are you sure?');");//Wait for the alert to be displayed
wait =newWebDriverWait(driver,Duration.ofSeconds(30));
wait.until(ExpectedConditions.alertIsPresent());
alert = driver.switchTo().alert();//Store the alert text in a variable and verify it
text = alert.getText();assertEquals(text,"Are you sure?");//Press the Cancel button
alert.dismiss();//Prompt//execute js for prompt
js.executeScript("prompt('What is your name?');");//Wait for the alert to be displayed and store it in a variable
wait =newWebDriverWait(driver,Duration.ofSeconds(30));
wait.until(ExpectedConditions.alertIsPresent());
alert = driver.switchTo().alert();//Store the alert text in a variable and verify it
text = alert.getText();assertEquals(text,"What is your name?");//Type your message
alert.sendKeys("Selenium");//Press the OK button
alert.accept();//quit the browser
driver.quit();}}
element = driver.find_element(By.LINK_TEXT,"See a sample prompt")
driver.execute_script("arguments[0].click();", element)
wait = WebDriverWait(driver, timeout=2)
alert = wait.until(lambda d : d.switch_to.alert)
alert.send_keys("Selenium")
text = alert.text
alert.accept()
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
global url
url ="https://www.selenium.dev/documentation/webdriver/interactions/alerts/"deftest_alert_popup():
driver = webdriver.Chrome()
driver.get(url)
element = driver.find_element(By.LINK_TEXT,"See an example alert")
element.click()
wait = WebDriverWait(driver, timeout=2)
alert = wait.until(lambda d : d.switch_to.alert)
text = alert.text
alert.accept()assert text =="Sample alert"
driver.quit()deftest_confirm_popup():
driver = webdriver.Chrome()
driver.get(url)
element = driver.find_element(By.LINK_TEXT,"See a sample confirm")
driver.execute_script("arguments[0].click();", element)
wait = WebDriverWait(driver, timeout=2)
alert = wait.until(lambda d : d.switch_to.alert)
text = alert.text
alert.dismiss()assert text =="Are you sure?"
driver.quit()deftest_prompt_popup():
driver = webdriver.Chrome()
driver.get(url)
element = driver.find_element(By.LINK_TEXT,"See a sample prompt")
driver.execute_script("arguments[0].click();", element)
wait = WebDriverWait(driver, timeout=2)
alert = wait.until(lambda d : d.switch_to.alert)
alert.send_keys("Selenium")
text = alert.text
alert.accept()assert text =="What is your tool of choice?"
driver.quit()
//Click the link to activate the alert
driver.FindElement(By.LinkText("See a sample prompt")).Click();//Wait for the alert to be displayed and store it in a variableIAlert alert = wait.Until(ExpectedConditions.AlertIsPresent());//Type your message
alert.SendKeys("Selenium");//Press the OK button
alert.Accept();
# Store the alert reference in a variable
alert = driver.switch_to.alert
# Type a message
alert.send_keys('selenium')# Press on Ok button
alert.accept
# frozen_string_literal: truerequire'spec_helper'RSpec.describe 'Alerts'do
let(:driver){ start_session }
before do
driver.navigate.to 'https://selenium.dev'end
it 'interacts with an alert'do
driver.execute_script 'alert("Hello, World!")'# Store the alert reference in a variable
alert = driver.switch_to.alert
# Get the text of the alert
alert.text
# Press on Cancel button
alert.dismiss
end
it 'interacts with a confirm'do
driver.execute_script 'confirm("Are you sure?")'# Store the alert reference in a variable
alert = driver.switch_to.alert
# Get the text of the alert
alert.text
# Press on Cancel button
alert.dismiss
end
it 'interacts with a prompt'do
driver.execute_script 'prompt("What is your name?")'# Store the alert reference in a variable
alert = driver.switch_to.alert
# Type a message
alert.send_keys('selenium')# Press on Ok button
alert.accept
endend
let alert =await driver.switchTo().alert();//Type your messageawait alert.sendKeys(text);await alert.accept();
const{ By, Builder, until }=require('selenium-webdriver');const assert =require("node:assert");describe('Interactions - Alerts',function(){let driver;before(asyncfunction(){
driver =awaitnewBuilder().forBrowser('chrome').build();});after(async()=>await driver.quit());it('Should be able to getText from alert and accept',asyncfunction(){await driver.get('https://www.selenium.dev/selenium/web/alerts.html');await driver.findElement(By.id("alert")).click();await driver.wait(until.alertIsPresent());let alert =await driver.switchTo().alert();let alertText =await alert.getText();await alert.accept();// Verify
assert.equal(alertText,"cheese");});it('Should be able to getText from alert and dismiss',asyncfunction(){await driver.get('https://www.selenium.dev/selenium/web/alerts.html');await driver.findElement(By.id("confirm")).click();await driver.wait(until.alertIsPresent());let alert =await driver.switchTo().alert();let alertText =await alert.getText();await alert.dismiss();// Verify
assert.equal(alertText,"Are you sure?");});it('Should be able to enter text in alert prompt',asyncfunction(){let text ='Selenium';await driver.get('https://www.selenium.dev/selenium/web/alerts.html');await driver.findElement(By.id("prompt")).click();await driver.wait(until.alertIsPresent());let alert =await driver.switchTo().alert();//Type your messageawait alert.sendKeys(text);await alert.accept();let enteredText =await driver.findElement(By.id('text'));
assert.equal(await enteredText.getText(), text);});});
//Click the link to activate the alert
driver.findElement(By.linkText("See a sample prompt")).click()//Wait for the alert to be displayed and store it in a variableval alert = wait.until(ExpectedConditions.alertIsPresent())//Type your message
alert.sendKeys("Selenium")//Press the OK button
alert.accept()
3 - Trabalhando com cookies
Um cookie é um pequeno pedaço de dado enviado de um site e armazenado no seu computador.
Os cookies são usados principalmente para reconhecer o usuário e carregar as informações armazenadas.
A API WebDriver fornece uma maneira de interagir com cookies com métodos integrados:
Add Cookie
É usado para adicionar um cookie ao contexto de navegação atual.
Add Cookie aceita apenas um conjunto de objetos JSON serializáveis definidos. Aqui é o link para a lista de valores-chave JSON aceitos.
Em primeiro lugar, você precisa estar no domínio para qual o cookie será
valido. Se você está tentando predefinir cookies antes
de começar a interagir com um site e sua página inicial é grande / demora um pouco para carregar
uma alternativa é encontrar uma página menor no site (normalmente a página 404 é pequena,
por exemplo http://example.com/some404page)
driver.get("https://www.selenium.dev/selenium/web/blank.html");// Add cookie into current browser context
driver.manage().addCookie(newCookie("key","value"));
// Licensed to the Software Freedom Conservancy (SFC) under one// or more contributor license agreements. See the NOTICE file// distributed with this work for additional information// regarding copyright ownership. The SFC licenses this file// to you under the Apache License, Version 2.0 (the// "License"); you may not use this file except in compliance// with the License. You may obtain a copy of the License at//// http://www.apache.org/licenses/LICENSE-2.0//// Unless required by applicable law or agreed to in writing,// software distributed under the License is distributed on an// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY// KIND, either express or implied. See the License for the// specific language governing permissions and limitations// under the License.importorg.junit.jupiter.api.Test;importorg.junit.jupiter.api.Assertions;importorg.openqa.selenium.Cookie;importorg.openqa.selenium.WebDriver;importorg.openqa.selenium.chrome.ChromeDriver;importjava.util.Set;publicclassCookiesTest{WebDriver driver =newChromeDriver();@TestpublicvoidaddCookie(){
driver.get("https://www.selenium.dev/selenium/web/blank.html");// Add cookie into current browser context
driver.manage().addCookie(newCookie("key","value"));
driver.quit();}@TestpublicvoidgetNamedCookie(){
driver.get("https://www.selenium.dev/selenium/web/blank.html");// Add cookie into current browser context
driver.manage().addCookie(newCookie("foo","bar"));// Get cookie details with named cookie 'foo'Cookie cookie = driver.manage().getCookieNamed("foo");Assertions.assertEquals(cookie.getValue(),"bar");
driver.quit();}@TestpublicvoidgetAllCookies(){
driver.get("https://www.selenium.dev/selenium/web/blank.html");// Add cookies into current browser context
driver.manage().addCookie(newCookie("test1","cookie1"));
driver.manage().addCookie(newCookie("test2","cookie2"));// Get cookiesSet<Cookie> cookies = driver.manage().getCookies();for(Cookie cookie : cookies){if(cookie.getName().equals("test1")){Assertions.assertEquals(cookie.getValue(),"cookie1");}if(cookie.getName().equals("test2")){Assertions.assertEquals(cookie.getValue(),"cookie2");}}
driver.quit();}@TestpublicvoiddeleteCookieNamed(){
driver.get("https://www.selenium.dev/selenium/web/blank.html");
driver.manage().addCookie(newCookie("test1","cookie1"));// delete cookie named
driver.manage().deleteCookieNamed("test1");
driver.quit();}@TestpublicvoiddeleteCookieObject(){
driver.get("https://www.selenium.dev/selenium/web/blank.html");Cookie cookie =newCookie("test2","cookie2");
driver.manage().addCookie(cookie);/*
Selenium Java bindings also provides a way to delete
cookie by passing cookie object of current browsing context
*/
driver.manage().deleteCookie(cookie);
driver.quit();}@TestpublicvoiddeleteAllCookies(){
driver.get("https://www.selenium.dev/selenium/web/blank.html");// Add cookies into current browser context
driver.manage().addCookie(newCookie("test1","cookie1"));
driver.manage().addCookie(newCookie("test2","cookie2"));// Delete All cookies
driver.manage().deleteAllCookies();
driver.quit();}@TestpublicvoidsameSiteCookie(){
driver.get("http://www.example.com");Cookie cookie =newCookie.Builder("key","value").sameSite("Strict").build();Cookie cookie1 =newCookie.Builder("key","value").sameSite("Lax").build();
driver.manage().addCookie(cookie);
driver.manage().addCookie(cookie1);System.out.println(cookie.getSameSite());System.out.println(cookie1.getSameSite());
driver.quit();}}
driver = webdriver.Chrome()
driver.get("http://www.example.com")# Adds the cookie into current browser context
driver.add_cookie({"name":"key","value":"value"})
from selenium import webdriver
deftest_add_cookie():
driver = webdriver.Chrome()
driver.get("http://www.example.com")# Adds the cookie into current browser context
driver.add_cookie({"name":"key","value":"value"})deftest_get_named_cookie():
driver = webdriver.Chrome()
driver.get("http://www.example.com")# Adds the cookie into current browser context
driver.add_cookie({"name":"foo","value":"bar"})# Get cookie details with named cookie 'foo'print(driver.get_cookie("foo"))deftest_get_all_cookies():
driver = webdriver.Chrome()
driver.get("http://www.example.com")
driver.add_cookie({"name":"test1","value":"cookie1"})
driver.add_cookie({"name":"test2","value":"cookie2"})# Get all available cookiesprint(driver.get_cookies())deftest_delete_cookie():
driver = webdriver.Chrome()
driver.get("http://www.example.com")
driver.add_cookie({"name":"test1","value":"cookie1"})
driver.add_cookie({"name":"test2","value":"cookie2"})# Delete cookie with name 'test1'
driver.delete_cookie("test1")deftest_delete_all_cookies():
driver = webdriver.Chrome()
driver.get("http://www.example.com")
driver.add_cookie({"name":"test1","value":"cookie1"})
driver.add_cookie({"name":"test2","value":"cookie2"})# Delete all cookies
driver.delete_all_cookies()deftest_same_side_cookie_attr():
driver = webdriver.Chrome()
driver.get("http://www.example.com")# Adds the cookie into current browser context with sameSite 'Strict' (or) 'Lax'
driver.add_cookie({"name":"foo","value":"value","sameSite":"Strict"})
driver.add_cookie({"name":"foo1","value":"value","sameSite":"Lax"})
cookie1 = driver.get_cookie("foo")
cookie2 = driver.get_cookie("foo1")print(cookie1)print(cookie2)
driver.Url="https://www.selenium.dev/selenium/web/blank.html";// Add cookie into current browser context
driver.Manage().Cookies.AddCookie(newCookie("key","value"));
// Licensed to the Software Freedom Conservancy (SFC) under one// or more contributor license agreements. See the NOTICE file// distributed with this work for additional information// regarding copyright ownership. The SFC licenses this file// to you under the Apache License, Version 2.0 (the// "License"); you may not use this file except in compliance// with the License. You may obtain a copy of the License at//// http://www.apache.org/licenses/LICENSE-2.0//// Unless required by applicable law or agreed to in writing,// software distributed under the License is distributed on an// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY// KIND, either express or implied. See the License for the// specific language governing permissions and limitations// under the License.usingSystem;usingMicrosoft.VisualStudio.TestTools.UnitTesting;usingOpenQA.Selenium;usingOpenQA.Selenium.Chrome;namespaceSeleniumDocs.Interactions{[TestClass]publicclassCookiesTest{WebDriver driver =newChromeDriver();[TestMethod]publicvoidaddCookie(){
driver.Url="https://www.selenium.dev/selenium/web/blank.html";// Add cookie into current browser context
driver.Manage().Cookies.AddCookie(newCookie("key","value"));
driver.Quit();}[TestMethod]publicvoidgetNamedCookie(){
driver.Url ="https://www.selenium.dev/selenium/web/blank.html";// Add cookie into current browser context
driver.Manage().Cookies.AddCookie(newCookie("foo","bar"));// Get cookie details with named cookie 'foo'Cookie cookie = driver.Manage().Cookies.GetCookieNamed("foo");
Assert.AreEqual(cookie.Value,"bar");
driver.Quit();}[TestMethod]publicvoidgetAllCookies(){
driver.Url ="https://www.selenium.dev/selenium/web/blank.html";// Add cookies into current browser context
driver.Manage().Cookies.AddCookie(newCookie("test1","cookie1"));
driver.Manage().Cookies.AddCookie(newCookie("test2","cookie2"));// Get cookiesvar cookies = driver.Manage().Cookies.AllCookies;foreach(var cookie in cookies){if(cookie.Name.Equals("test1")){
Assert.AreEqual("cookie1", cookie.Value);}if(cookie.Name.Equals("test2")){
Assert.AreEqual("cookie2", cookie.Value);}}
driver.Quit();}[TestMethod]publicvoiddeleteCookieNamed(){
driver.Url ="https://www.selenium.dev/selenium/web/blank.html";
driver.Manage().Cookies.AddCookie(newCookie("test1","cookie1"));// delete cookie named
driver.Manage().Cookies.DeleteCookieNamed("test1");
driver.Quit();}[TestMethod]publicvoiddeleteCookieObject(){
driver.Url ="https://www.selenium.dev/selenium/web/blank.html";Cookie cookie =newCookie("test2","cookie2");
driver.Manage().Cookies.AddCookie(cookie);/*
Selenium CSharp bindings also provides a way to delete
cookie by passing cookie object of current browsing context
*/
driver.Manage().Cookies.DeleteCookie(cookie);
driver.Quit();}[TestMethod]publicvoiddeleteAllCookies(){
driver.Url ="https://www.selenium.dev/selenium/web/blank.html";// Add cookies into current browser context
driver.Manage().Cookies.AddCookie(newCookie("test1","cookie1"));
driver.Manage().Cookies.AddCookie(newCookie("test2","cookie2"));// Delete All cookies
driver.Manage().Cookies.DeleteAllCookies();
driver.Quit();}}}
driver.navigate.to 'https://www.selenium.dev/selenium/web/blank.html'# Add cookie into current browser context
driver.manage.add_cookie(name:'key', value:'value')
# frozen_string_literal: truerequire'spec_helper'RSpec.describe 'Cookies'do
let(:driver){ start_session }
it 'adds a cookie'do
driver.navigate.to 'https://www.selenium.dev/selenium/web/blank.html'# Add cookie into current browser context
driver.manage.add_cookie(name:'key', value:'value')# Verify cookie was added
expect(driver.manage.cookie_named('key')[:value]).to eq('value')end
it 'gets a named cookie'do
driver.navigate.to 'https://www.selenium.dev/selenium/web/blank.html'# Add cookie into current browser context
driver.manage.add_cookie(name:'foo', value:'bar')# Get cookie details with named cookie 'foo'
cookie = driver.manage.cookie_named('foo')
expect(cookie[:value]).to eq('bar')end
it 'gets all cookies'do
driver.navigate.to 'https://www.selenium.dev/selenium/web/blank.html'# Add cookies into current browser context
driver.manage.add_cookie(name:'test1', value:'cookie1')
driver.manage.add_cookie(name:'test2', value:'cookie2')# Get cookies
cookies = driver.manage.all_cookies
# Verify both cookies exist with correct values
test1_cookie = cookies.find {|c| c[:name]=='test1'}
test2_cookie = cookies.find {|c| c[:name]=='test2'}
expect(test1_cookie[:value]).to eq('cookie1')
expect(test2_cookie[:value]).to eq('cookie2')end
it 'deletes a cookie by name'do
driver.navigate.to 'https://www.selenium.dev/selenium/web/blank.html'
driver.manage.add_cookie(name:'test1', value:'cookie1')# Delete cookie named
driver.manage.delete_cookie('test1')# Verify cookie is deleted
expect { driver.manage.cookie_named('test1')}.to raise_error(Selenium::WebDriver::Error::NoSuchCookieError)end
it 'deletes all cookies'do
driver.navigate.to 'https://www.selenium.dev/selenium/web/blank.html'# Add cookies into current browser context
driver.manage.add_cookie(name:'test1', value:'cookie1')
driver.manage.add_cookie(name:'test2', value:'cookie2')# Delete All cookies
driver.manage.delete_all_cookies
# Verify all cookies are deleted
expect(driver.manage.all_cookies.size).to eq(0)endend
const{Browser, Builder}=require("selenium-webdriver");const assert =require('assert')describe('Cookies',function(){let driver;before(asyncfunction(){
driver =newBuilder().forBrowser(Browser.CHROME).build();});after(async()=>await driver.quit());it('Create a cookie',asyncfunction(){await driver.get('https://www.selenium.dev/selenium/web/blank.html');// set a cookie on the current domainawait driver.manage().addCookie({name:'key',value:'value'});});it('Create cookies with sameSite',asyncfunction(){await driver.get('https://www.selenium.dev/selenium/web/blank.html');// set a cookie on the current domain with sameSite 'Strict' (or) 'Lax'await driver.manage().addCookie({name:'key',value:'value',sameSite:'Strict'});await driver.manage().addCookie({name:'key',value:'value',sameSite:'Lax'});});it('Read cookie',asyncfunction(){await driver.get('https://www.selenium.dev/selenium/web/blank.html');// set a cookie on the current domainawait driver.manage().addCookie({name:'foo',value:'bar'});// Get cookie details with named cookie 'foo'await driver.manage().getCookie('foo').then(function(cookie){
assert.equal(cookie.value,'bar');});});it('Read all cookies',asyncfunction(){await driver.get('https://www.selenium.dev/selenium/web/blank.html');// Add few cookiesawait driver.manage().addCookie({name:'test1',value:'cookie1'});await driver.manage().addCookie({name:'test2',value:'cookie2'});// Get all Available cookiesawait driver.manage().getCookies().then(function(cookies){
assert.equal(cookies.filter(cookie=> cookie.name.startsWith('test')).length,2);});});it('Delete a cookie',asyncfunction(){await driver.get('https://www.selenium.dev/selenium/web/blank.html');// Add few cookiesawait driver.manage().addCookie({name:'test1',value:'cookie1'});await driver.manage().addCookie({name:'test2',value:'cookie2'});// Delete a cookie with name 'test1'await driver.manage().deleteCookie('test1');// Get all Available cookiesawait driver.manage().getCookies().then(function(cookies){
assert.equal(cookies.filter(cookie=> cookie.name.startsWith('test')).length,1);});});it('Delete all cookies',asyncfunction(){await driver.get('https://www.selenium.dev/selenium/web/blank.html');// Add few cookiesawait driver.manage().addCookie({name:'test1',value:'cookie1'});await driver.manage().addCookie({name:'test2',value:'cookie2'});// Delete all cookiesawait driver.manage().deleteAllCookies();});});
import org.openqa.selenium.Cookie
import org.openqa.selenium.chrome.ChromeDriver
funmain(){val driver =ChromeDriver()try{
driver.get("https://example.com")// Adds the cookie into current browser context
driver.manage().addCookie(Cookie("key","value"))}finally{
driver.quit()}}
Get Named Cookie
Retorna os dados do cookie serializado correspondentes ao nome do cookie entre todos os cookies associados.
driver.get("https://www.selenium.dev/selenium/web/blank.html");// Add cookie into current browser context
driver.manage().addCookie(newCookie("foo","bar"));// Get cookie details with named cookie 'foo'Cookie cookie = driver.manage().getCookieNamed("foo");
// Licensed to the Software Freedom Conservancy (SFC) under one// or more contributor license agreements. See the NOTICE file// distributed with this work for additional information// regarding copyright ownership. The SFC licenses this file// to you under the Apache License, Version 2.0 (the// "License"); you may not use this file except in compliance// with the License. You may obtain a copy of the License at//// http://www.apache.org/licenses/LICENSE-2.0//// Unless required by applicable law or agreed to in writing,// software distributed under the License is distributed on an// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY// KIND, either express or implied. See the License for the// specific language governing permissions and limitations// under the License.importorg.junit.jupiter.api.Test;importorg.junit.jupiter.api.Assertions;importorg.openqa.selenium.Cookie;importorg.openqa.selenium.WebDriver;importorg.openqa.selenium.chrome.ChromeDriver;importjava.util.Set;publicclassCookiesTest{WebDriver driver =newChromeDriver();@TestpublicvoidaddCookie(){
driver.get("https://www.selenium.dev/selenium/web/blank.html");// Add cookie into current browser context
driver.manage().addCookie(newCookie("key","value"));
driver.quit();}@TestpublicvoidgetNamedCookie(){
driver.get("https://www.selenium.dev/selenium/web/blank.html");// Add cookie into current browser context
driver.manage().addCookie(newCookie("foo","bar"));// Get cookie details with named cookie 'foo'Cookie cookie = driver.manage().getCookieNamed("foo");Assertions.assertEquals(cookie.getValue(),"bar");
driver.quit();}@TestpublicvoidgetAllCookies(){
driver.get("https://www.selenium.dev/selenium/web/blank.html");// Add cookies into current browser context
driver.manage().addCookie(newCookie("test1","cookie1"));
driver.manage().addCookie(newCookie("test2","cookie2"));// Get cookiesSet<Cookie> cookies = driver.manage().getCookies();for(Cookie cookie : cookies){if(cookie.getName().equals("test1")){Assertions.assertEquals(cookie.getValue(),"cookie1");}if(cookie.getName().equals("test2")){Assertions.assertEquals(cookie.getValue(),"cookie2");}}
driver.quit();}@TestpublicvoiddeleteCookieNamed(){
driver.get("https://www.selenium.dev/selenium/web/blank.html");
driver.manage().addCookie(newCookie("test1","cookie1"));// delete cookie named
driver.manage().deleteCookieNamed("test1");
driver.quit();}@TestpublicvoiddeleteCookieObject(){
driver.get("https://www.selenium.dev/selenium/web/blank.html");Cookie cookie =newCookie("test2","cookie2");
driver.manage().addCookie(cookie);/*
Selenium Java bindings also provides a way to delete
cookie by passing cookie object of current browsing context
*/
driver.manage().deleteCookie(cookie);
driver.quit();}@TestpublicvoiddeleteAllCookies(){
driver.get("https://www.selenium.dev/selenium/web/blank.html");// Add cookies into current browser context
driver.manage().addCookie(newCookie("test1","cookie1"));
driver.manage().addCookie(newCookie("test2","cookie2"));// Delete All cookies
driver.manage().deleteAllCookies();
driver.quit();}@TestpublicvoidsameSiteCookie(){
driver.get("http://www.example.com");Cookie cookie =newCookie.Builder("key","value").sameSite("Strict").build();Cookie cookie1 =newCookie.Builder("key","value").sameSite("Lax").build();
driver.manage().addCookie(cookie);
driver.manage().addCookie(cookie1);System.out.println(cookie.getSameSite());System.out.println(cookie1.getSameSite());
driver.quit();}}
driver = webdriver.Chrome()
driver.get("http://www.example.com")# Adds the cookie into current browser context
driver.add_cookie({"name":"foo","value":"bar"})# Get cookie details with named cookie 'foo'print(driver.get_cookie("foo"))
from selenium import webdriver
deftest_add_cookie():
driver = webdriver.Chrome()
driver.get("http://www.example.com")# Adds the cookie into current browser context
driver.add_cookie({"name":"key","value":"value"})deftest_get_named_cookie():
driver = webdriver.Chrome()
driver.get("http://www.example.com")# Adds the cookie into current browser context
driver.add_cookie({"name":"foo","value":"bar"})# Get cookie details with named cookie 'foo'print(driver.get_cookie("foo"))deftest_get_all_cookies():
driver = webdriver.Chrome()
driver.get("http://www.example.com")
driver.add_cookie({"name":"test1","value":"cookie1"})
driver.add_cookie({"name":"test2","value":"cookie2"})# Get all available cookiesprint(driver.get_cookies())deftest_delete_cookie():
driver = webdriver.Chrome()
driver.get("http://www.example.com")
driver.add_cookie({"name":"test1","value":"cookie1"})
driver.add_cookie({"name":"test2","value":"cookie2"})# Delete cookie with name 'test1'
driver.delete_cookie("test1")deftest_delete_all_cookies():
driver = webdriver.Chrome()
driver.get("http://www.example.com")
driver.add_cookie({"name":"test1","value":"cookie1"})
driver.add_cookie({"name":"test2","value":"cookie2"})# Delete all cookies
driver.delete_all_cookies()deftest_same_side_cookie_attr():
driver = webdriver.Chrome()
driver.get("http://www.example.com")# Adds the cookie into current browser context with sameSite 'Strict' (or) 'Lax'
driver.add_cookie({"name":"foo","value":"value","sameSite":"Strict"})
driver.add_cookie({"name":"foo1","value":"value","sameSite":"Lax"})
cookie1 = driver.get_cookie("foo")
cookie2 = driver.get_cookie("foo1")print(cookie1)print(cookie2)
driver.Url ="https://www.selenium.dev/selenium/web/blank.html";// Add cookie into current browser context
driver.Manage().Cookies.AddCookie(newCookie("foo","bar"));// Get cookie details with named cookie 'foo'Cookie cookie = driver.Manage().Cookies.GetCookieNamed("foo");
// Licensed to the Software Freedom Conservancy (SFC) under one// or more contributor license agreements. See the NOTICE file// distributed with this work for additional information// regarding copyright ownership. The SFC licenses this file// to you under the Apache License, Version 2.0 (the// "License"); you may not use this file except in compliance// with the License. You may obtain a copy of the License at//// http://www.apache.org/licenses/LICENSE-2.0//// Unless required by applicable law or agreed to in writing,// software distributed under the License is distributed on an// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY// KIND, either express or implied. See the License for the// specific language governing permissions and limitations// under the License.usingSystem;usingMicrosoft.VisualStudio.TestTools.UnitTesting;usingOpenQA.Selenium;usingOpenQA.Selenium.Chrome;namespaceSeleniumDocs.Interactions{[TestClass]publicclassCookiesTest{WebDriver driver =newChromeDriver();[TestMethod]publicvoidaddCookie(){
driver.Url="https://www.selenium.dev/selenium/web/blank.html";// Add cookie into current browser context
driver.Manage().Cookies.AddCookie(newCookie("key","value"));
driver.Quit();}[TestMethod]publicvoidgetNamedCookie(){
driver.Url ="https://www.selenium.dev/selenium/web/blank.html";// Add cookie into current browser context
driver.Manage().Cookies.AddCookie(newCookie("foo","bar"));// Get cookie details with named cookie 'foo'Cookie cookie = driver.Manage().Cookies.GetCookieNamed("foo");
Assert.AreEqual(cookie.Value,"bar");
driver.Quit();}[TestMethod]publicvoidgetAllCookies(){
driver.Url ="https://www.selenium.dev/selenium/web/blank.html";// Add cookies into current browser context
driver.Manage().Cookies.AddCookie(newCookie("test1","cookie1"));
driver.Manage().Cookies.AddCookie(newCookie("test2","cookie2"));// Get cookiesvar cookies = driver.Manage().Cookies.AllCookies;foreach(var cookie in cookies){if(cookie.Name.Equals("test1")){
Assert.AreEqual("cookie1", cookie.Value);}if(cookie.Name.Equals("test2")){
Assert.AreEqual("cookie2", cookie.Value);}}
driver.Quit();}[TestMethod]publicvoiddeleteCookieNamed(){
driver.Url ="https://www.selenium.dev/selenium/web/blank.html";
driver.Manage().Cookies.AddCookie(newCookie("test1","cookie1"));// delete cookie named
driver.Manage().Cookies.DeleteCookieNamed("test1");
driver.Quit();}[TestMethod]publicvoiddeleteCookieObject(){
driver.Url ="https://www.selenium.dev/selenium/web/blank.html";Cookie cookie =newCookie("test2","cookie2");
driver.Manage().Cookies.AddCookie(cookie);/*
Selenium CSharp bindings also provides a way to delete
cookie by passing cookie object of current browsing context
*/
driver.Manage().Cookies.DeleteCookie(cookie);
driver.Quit();}[TestMethod]publicvoiddeleteAllCookies(){
driver.Url ="https://www.selenium.dev/selenium/web/blank.html";// Add cookies into current browser context
driver.Manage().Cookies.AddCookie(newCookie("test1","cookie1"));
driver.Manage().Cookies.AddCookie(newCookie("test2","cookie2"));// Delete All cookies
driver.Manage().Cookies.DeleteAllCookies();
driver.Quit();}}}
driver.navigate.to 'https://www.selenium.dev/selenium/web/blank.html'# Add cookie into current browser context
driver.manage.add_cookie(name:'foo', value:'bar')# Get cookie details with named cookie 'foo'
cookie = driver.manage.cookie_named('foo')
# frozen_string_literal: truerequire'spec_helper'RSpec.describe 'Cookies'do
let(:driver){ start_session }
it 'adds a cookie'do
driver.navigate.to 'https://www.selenium.dev/selenium/web/blank.html'# Add cookie into current browser context
driver.manage.add_cookie(name:'key', value:'value')# Verify cookie was added
expect(driver.manage.cookie_named('key')[:value]).to eq('value')end
it 'gets a named cookie'do
driver.navigate.to 'https://www.selenium.dev/selenium/web/blank.html'# Add cookie into current browser context
driver.manage.add_cookie(name:'foo', value:'bar')# Get cookie details with named cookie 'foo'
cookie = driver.manage.cookie_named('foo')
expect(cookie[:value]).to eq('bar')end
it 'gets all cookies'do
driver.navigate.to 'https://www.selenium.dev/selenium/web/blank.html'# Add cookies into current browser context
driver.manage.add_cookie(name:'test1', value:'cookie1')
driver.manage.add_cookie(name:'test2', value:'cookie2')# Get cookies
cookies = driver.manage.all_cookies
# Verify both cookies exist with correct values
test1_cookie = cookies.find {|c| c[:name]=='test1'}
test2_cookie = cookies.find {|c| c[:name]=='test2'}
expect(test1_cookie[:value]).to eq('cookie1')
expect(test2_cookie[:value]).to eq('cookie2')end
it 'deletes a cookie by name'do
driver.navigate.to 'https://www.selenium.dev/selenium/web/blank.html'
driver.manage.add_cookie(name:'test1', value:'cookie1')# Delete cookie named
driver.manage.delete_cookie('test1')# Verify cookie is deleted
expect { driver.manage.cookie_named('test1')}.to raise_error(Selenium::WebDriver::Error::NoSuchCookieError)end
it 'deletes all cookies'do
driver.navigate.to 'https://www.selenium.dev/selenium/web/blank.html'# Add cookies into current browser context
driver.manage.add_cookie(name:'test1', value:'cookie1')
driver.manage.add_cookie(name:'test2', value:'cookie2')# Delete All cookies
driver.manage.delete_all_cookies
# Verify all cookies are deleted
expect(driver.manage.all_cookies.size).to eq(0)endend
// set a cookie on the current domainawait driver.manage().addCookie({name:'foo',value:'bar'});// Get cookie details with named cookie 'foo'
const{Browser, Builder}=require("selenium-webdriver");const assert =require('assert')describe('Cookies',function(){let driver;before(asyncfunction(){
driver =newBuilder().forBrowser(Browser.CHROME).build();});after(async()=>await driver.quit());it('Create a cookie',asyncfunction(){await driver.get('https://www.selenium.dev/selenium/web/blank.html');// set a cookie on the current domainawait driver.manage().addCookie({name:'key',value:'value'});});it('Create cookies with sameSite',asyncfunction(){await driver.get('https://www.selenium.dev/selenium/web/blank.html');// set a cookie on the current domain with sameSite 'Strict' (or) 'Lax'await driver.manage().addCookie({name:'key',value:'value',sameSite:'Strict'});await driver.manage().addCookie({name:'key',value:'value',sameSite:'Lax'});});it('Read cookie',asyncfunction(){await driver.get('https://www.selenium.dev/selenium/web/blank.html');// set a cookie on the current domainawait driver.manage().addCookie({name:'foo',value:'bar'});// Get cookie details with named cookie 'foo'await driver.manage().getCookie('foo').then(function(cookie){
assert.equal(cookie.value,'bar');});});it('Read all cookies',asyncfunction(){await driver.get('https://www.selenium.dev/selenium/web/blank.html');// Add few cookiesawait driver.manage().addCookie({name:'test1',value:'cookie1'});await driver.manage().addCookie({name:'test2',value:'cookie2'});// Get all Available cookiesawait driver.manage().getCookies().then(function(cookies){
assert.equal(cookies.filter(cookie=> cookie.name.startsWith('test')).length,2);});});it('Delete a cookie',asyncfunction(){await driver.get('https://www.selenium.dev/selenium/web/blank.html');// Add few cookiesawait driver.manage().addCookie({name:'test1',value:'cookie1'});await driver.manage().addCookie({name:'test2',value:'cookie2'});// Delete a cookie with name 'test1'await driver.manage().deleteCookie('test1');// Get all Available cookiesawait driver.manage().getCookies().then(function(cookies){
assert.equal(cookies.filter(cookie=> cookie.name.startsWith('test')).length,1);});});it('Delete all cookies',asyncfunction(){await driver.get('https://www.selenium.dev/selenium/web/blank.html');// Add few cookiesawait driver.manage().addCookie({name:'test1',value:'cookie1'});await driver.manage().addCookie({name:'test2',value:'cookie2'});// Delete all cookiesawait driver.manage().deleteAllCookies();});});
import org.openqa.selenium.Cookie
import org.openqa.selenium.chrome.ChromeDriver
funmain(){val driver =ChromeDriver()try{
driver.get("https://example.com")
driver.manage().addCookie(Cookie("foo","bar"))// Get cookie details with named cookie 'foo'val cookie = driver.manage().getCookieNamed("foo")println(cookie)}finally{
driver.quit()}}
Get All Cookies
Retorna ‘dados de cookie serializados com sucesso’ para o contexto de navegação atual.
Se o navegador não estiver mais disponível, ele retornará um erro.
driver.get("https://www.selenium.dev/selenium/web/blank.html");// Add cookies into current browser context
driver.manage().addCookie(newCookie("test1","cookie1"));
driver.manage().addCookie(newCookie("test2","cookie2"));// Get cookiesSet<Cookie> cookies = driver.manage().getCookies();for(Cookie cookie : cookies){if(cookie.getName().equals("test1")){Assertions.assertEquals(cookie.getValue(),"cookie1");}if(cookie.getName().equals("test2")){Assertions.assertEquals(cookie.getValue(),"cookie2");}}
// Licensed to the Software Freedom Conservancy (SFC) under one// or more contributor license agreements. See the NOTICE file// distributed with this work for additional information// regarding copyright ownership. The SFC licenses this file// to you under the Apache License, Version 2.0 (the// "License"); you may not use this file except in compliance// with the License. You may obtain a copy of the License at//// http://www.apache.org/licenses/LICENSE-2.0//// Unless required by applicable law or agreed to in writing,// software distributed under the License is distributed on an// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY// KIND, either express or implied. See the License for the// specific language governing permissions and limitations// under the License.importorg.junit.jupiter.api.Test;importorg.junit.jupiter.api.Assertions;importorg.openqa.selenium.Cookie;importorg.openqa.selenium.WebDriver;importorg.openqa.selenium.chrome.ChromeDriver;importjava.util.Set;publicclassCookiesTest{WebDriver driver =newChromeDriver();@TestpublicvoidaddCookie(){
driver.get("https://www.selenium.dev/selenium/web/blank.html");// Add cookie into current browser context
driver.manage().addCookie(newCookie("key","value"));
driver.quit();}@TestpublicvoidgetNamedCookie(){
driver.get("https://www.selenium.dev/selenium/web/blank.html");// Add cookie into current browser context
driver.manage().addCookie(newCookie("foo","bar"));// Get cookie details with named cookie 'foo'Cookie cookie = driver.manage().getCookieNamed("foo");Assertions.assertEquals(cookie.getValue(),"bar");
driver.quit();}@TestpublicvoidgetAllCookies(){
driver.get("https://www.selenium.dev/selenium/web/blank.html");// Add cookies into current browser context
driver.manage().addCookie(newCookie("test1","cookie1"));
driver.manage().addCookie(newCookie("test2","cookie2"));// Get cookiesSet<Cookie> cookies = driver.manage().getCookies();for(Cookie cookie : cookies){if(cookie.getName().equals("test1")){Assertions.assertEquals(cookie.getValue(),"cookie1");}if(cookie.getName().equals("test2")){Assertions.assertEquals(cookie.getValue(),"cookie2");}}
driver.quit();}@TestpublicvoiddeleteCookieNamed(){
driver.get("https://www.selenium.dev/selenium/web/blank.html");
driver.manage().addCookie(newCookie("test1","cookie1"));// delete cookie named
driver.manage().deleteCookieNamed("test1");
driver.quit();}@TestpublicvoiddeleteCookieObject(){
driver.get("https://www.selenium.dev/selenium/web/blank.html");Cookie cookie =newCookie("test2","cookie2");
driver.manage().addCookie(cookie);/*
Selenium Java bindings also provides a way to delete
cookie by passing cookie object of current browsing context
*/
driver.manage().deleteCookie(cookie);
driver.quit();}@TestpublicvoiddeleteAllCookies(){
driver.get("https://www.selenium.dev/selenium/web/blank.html");// Add cookies into current browser context
driver.manage().addCookie(newCookie("test1","cookie1"));
driver.manage().addCookie(newCookie("test2","cookie2"));// Delete All cookies
driver.manage().deleteAllCookies();
driver.quit();}@TestpublicvoidsameSiteCookie(){
driver.get("http://www.example.com");Cookie cookie =newCookie.Builder("key","value").sameSite("Strict").build();Cookie cookie1 =newCookie.Builder("key","value").sameSite("Lax").build();
driver.manage().addCookie(cookie);
driver.manage().addCookie(cookie1);System.out.println(cookie.getSameSite());System.out.println(cookie1.getSameSite());
driver.quit();}}
driver = webdriver.Chrome()
driver.get("http://www.example.com")
driver.add_cookie({"name":"test1","value":"cookie1"})
driver.add_cookie({"name":"test2","value":"cookie2"})# Get all available cookiesprint(driver.get_cookies())
from selenium import webdriver
deftest_add_cookie():
driver = webdriver.Chrome()
driver.get("http://www.example.com")# Adds the cookie into current browser context
driver.add_cookie({"name":"key","value":"value"})deftest_get_named_cookie():
driver = webdriver.Chrome()
driver.get("http://www.example.com")# Adds the cookie into current browser context
driver.add_cookie({"name":"foo","value":"bar"})# Get cookie details with named cookie 'foo'print(driver.get_cookie("foo"))deftest_get_all_cookies():
driver = webdriver.Chrome()
driver.get("http://www.example.com")
driver.add_cookie({"name":"test1","value":"cookie1"})
driver.add_cookie({"name":"test2","value":"cookie2"})# Get all available cookiesprint(driver.get_cookies())deftest_delete_cookie():
driver = webdriver.Chrome()
driver.get("http://www.example.com")
driver.add_cookie({"name":"test1","value":"cookie1"})
driver.add_cookie({"name":"test2","value":"cookie2"})# Delete cookie with name 'test1'
driver.delete_cookie("test1")deftest_delete_all_cookies():
driver = webdriver.Chrome()
driver.get("http://www.example.com")
driver.add_cookie({"name":"test1","value":"cookie1"})
driver.add_cookie({"name":"test2","value":"cookie2"})# Delete all cookies
driver.delete_all_cookies()deftest_same_side_cookie_attr():
driver = webdriver.Chrome()
driver.get("http://www.example.com")# Adds the cookie into current browser context with sameSite 'Strict' (or) 'Lax'
driver.add_cookie({"name":"foo","value":"value","sameSite":"Strict"})
driver.add_cookie({"name":"foo1","value":"value","sameSite":"Lax"})
cookie1 = driver.get_cookie("foo")
cookie2 = driver.get_cookie("foo1")print(cookie1)print(cookie2)
driver.Url ="https://www.selenium.dev/selenium/web/blank.html";// Add cookies into current browser context
driver.Manage().Cookies.AddCookie(newCookie("test1","cookie1"));
driver.Manage().Cookies.AddCookie(newCookie("test2","cookie2"));// Get cookiesvar cookies = driver.Manage().Cookies.AllCookies;foreach(var cookie in cookies){if(cookie.Name.Equals("test1")){
Assert.AreEqual("cookie1", cookie.Value);}if(cookie.Name.Equals("test2")){
Assert.AreEqual("cookie2", cookie.Value);}}
// Licensed to the Software Freedom Conservancy (SFC) under one// or more contributor license agreements. See the NOTICE file// distributed with this work for additional information// regarding copyright ownership. The SFC licenses this file// to you under the Apache License, Version 2.0 (the// "License"); you may not use this file except in compliance// with the License. You may obtain a copy of the License at//// http://www.apache.org/licenses/LICENSE-2.0//// Unless required by applicable law or agreed to in writing,// software distributed under the License is distributed on an// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY// KIND, either express or implied. See the License for the// specific language governing permissions and limitations// under the License.usingSystem;usingMicrosoft.VisualStudio.TestTools.UnitTesting;usingOpenQA.Selenium;usingOpenQA.Selenium.Chrome;namespaceSeleniumDocs.Interactions{[TestClass]publicclassCookiesTest{WebDriver driver =newChromeDriver();[TestMethod]publicvoidaddCookie(){
driver.Url="https://www.selenium.dev/selenium/web/blank.html";// Add cookie into current browser context
driver.Manage().Cookies.AddCookie(newCookie("key","value"));
driver.Quit();}[TestMethod]publicvoidgetNamedCookie(){
driver.Url ="https://www.selenium.dev/selenium/web/blank.html";// Add cookie into current browser context
driver.Manage().Cookies.AddCookie(newCookie("foo","bar"));// Get cookie details with named cookie 'foo'Cookie cookie = driver.Manage().Cookies.GetCookieNamed("foo");
Assert.AreEqual(cookie.Value,"bar");
driver.Quit();}[TestMethod]publicvoidgetAllCookies(){
driver.Url ="https://www.selenium.dev/selenium/web/blank.html";// Add cookies into current browser context
driver.Manage().Cookies.AddCookie(newCookie("test1","cookie1"));
driver.Manage().Cookies.AddCookie(newCookie("test2","cookie2"));// Get cookiesvar cookies = driver.Manage().Cookies.AllCookies;foreach(var cookie in cookies){if(cookie.Name.Equals("test1")){
Assert.AreEqual("cookie1", cookie.Value);}if(cookie.Name.Equals("test2")){
Assert.AreEqual("cookie2", cookie.Value);}}
driver.Quit();}[TestMethod]publicvoiddeleteCookieNamed(){
driver.Url ="https://www.selenium.dev/selenium/web/blank.html";
driver.Manage().Cookies.AddCookie(newCookie("test1","cookie1"));// delete cookie named
driver.Manage().Cookies.DeleteCookieNamed("test1");
driver.Quit();}[TestMethod]publicvoiddeleteCookieObject(){
driver.Url ="https://www.selenium.dev/selenium/web/blank.html";Cookie cookie =newCookie("test2","cookie2");
driver.Manage().Cookies.AddCookie(cookie);/*
Selenium CSharp bindings also provides a way to delete
cookie by passing cookie object of current browsing context
*/
driver.Manage().Cookies.DeleteCookie(cookie);
driver.Quit();}[TestMethod]publicvoiddeleteAllCookies(){
driver.Url ="https://www.selenium.dev/selenium/web/blank.html";// Add cookies into current browser context
driver.Manage().Cookies.AddCookie(newCookie("test1","cookie1"));
driver.Manage().Cookies.AddCookie(newCookie("test2","cookie2"));// Delete All cookies
driver.Manage().Cookies.DeleteAllCookies();
driver.Quit();}}}
driver.navigate.to 'https://www.selenium.dev/selenium/web/blank.html'# Add cookies into current browser context
driver.manage.add_cookie(name:'test1', value:'cookie1')
driver.manage.add_cookie(name:'test2', value:'cookie2')# Get cookies
cookies = driver.manage.all_cookies
# frozen_string_literal: truerequire'spec_helper'RSpec.describe 'Cookies'do
let(:driver){ start_session }
it 'adds a cookie'do
driver.navigate.to 'https://www.selenium.dev/selenium/web/blank.html'# Add cookie into current browser context
driver.manage.add_cookie(name:'key', value:'value')# Verify cookie was added
expect(driver.manage.cookie_named('key')[:value]).to eq('value')end
it 'gets a named cookie'do
driver.navigate.to 'https://www.selenium.dev/selenium/web/blank.html'# Add cookie into current browser context
driver.manage.add_cookie(name:'foo', value:'bar')# Get cookie details with named cookie 'foo'
cookie = driver.manage.cookie_named('foo')
expect(cookie[:value]).to eq('bar')end
it 'gets all cookies'do
driver.navigate.to 'https://www.selenium.dev/selenium/web/blank.html'# Add cookies into current browser context
driver.manage.add_cookie(name:'test1', value:'cookie1')
driver.manage.add_cookie(name:'test2', value:'cookie2')# Get cookies
cookies = driver.manage.all_cookies
# Verify both cookies exist with correct values
test1_cookie = cookies.find {|c| c[:name]=='test1'}
test2_cookie = cookies.find {|c| c[:name]=='test2'}
expect(test1_cookie[:value]).to eq('cookie1')
expect(test2_cookie[:value]).to eq('cookie2')end
it 'deletes a cookie by name'do
driver.navigate.to 'https://www.selenium.dev/selenium/web/blank.html'
driver.manage.add_cookie(name:'test1', value:'cookie1')# Delete cookie named
driver.manage.delete_cookie('test1')# Verify cookie is deleted
expect { driver.manage.cookie_named('test1')}.to raise_error(Selenium::WebDriver::Error::NoSuchCookieError)end
it 'deletes all cookies'do
driver.navigate.to 'https://www.selenium.dev/selenium/web/blank.html'# Add cookies into current browser context
driver.manage.add_cookie(name:'test1', value:'cookie1')
driver.manage.add_cookie(name:'test2', value:'cookie2')# Delete All cookies
driver.manage.delete_all_cookies
# Verify all cookies are deleted
expect(driver.manage.all_cookies.size).to eq(0)endend
await driver.manage().addCookie({name:'test2',value:'cookie2'});// Get all Available cookies
const{Browser, Builder}=require("selenium-webdriver");const assert =require('assert')describe('Cookies',function(){let driver;before(asyncfunction(){
driver =newBuilder().forBrowser(Browser.CHROME).build();});after(async()=>await driver.quit());it('Create a cookie',asyncfunction(){await driver.get('https://www.selenium.dev/selenium/web/blank.html');// set a cookie on the current domainawait driver.manage().addCookie({name:'key',value:'value'});});it('Create cookies with sameSite',asyncfunction(){await driver.get('https://www.selenium.dev/selenium/web/blank.html');// set a cookie on the current domain with sameSite 'Strict' (or) 'Lax'await driver.manage().addCookie({name:'key',value:'value',sameSite:'Strict'});await driver.manage().addCookie({name:'key',value:'value',sameSite:'Lax'});});it('Read cookie',asyncfunction(){await driver.get('https://www.selenium.dev/selenium/web/blank.html');// set a cookie on the current domainawait driver.manage().addCookie({name:'foo',value:'bar'});// Get cookie details with named cookie 'foo'await driver.manage().getCookie('foo').then(function(cookie){
assert.equal(cookie.value,'bar');});});it('Read all cookies',asyncfunction(){await driver.get('https://www.selenium.dev/selenium/web/blank.html');// Add few cookiesawait driver.manage().addCookie({name:'test1',value:'cookie1'});await driver.manage().addCookie({name:'test2',value:'cookie2'});// Get all Available cookiesawait driver.manage().getCookies().then(function(cookies){
assert.equal(cookies.filter(cookie=> cookie.name.startsWith('test')).length,2);});});it('Delete a cookie',asyncfunction(){await driver.get('https://www.selenium.dev/selenium/web/blank.html');// Add few cookiesawait driver.manage().addCookie({name:'test1',value:'cookie1'});await driver.manage().addCookie({name:'test2',value:'cookie2'});// Delete a cookie with name 'test1'await driver.manage().deleteCookie('test1');// Get all Available cookiesawait driver.manage().getCookies().then(function(cookies){
assert.equal(cookies.filter(cookie=> cookie.name.startsWith('test')).length,1);});});it('Delete all cookies',asyncfunction(){await driver.get('https://www.selenium.dev/selenium/web/blank.html');// Add few cookiesawait driver.manage().addCookie({name:'test1',value:'cookie1'});await driver.manage().addCookie({name:'test2',value:'cookie2'});// Delete all cookiesawait driver.manage().deleteAllCookies();});});
import org.openqa.selenium.Cookie
import org.openqa.selenium.chrome.ChromeDriver
funmain(){val driver =ChromeDriver()try{
driver.get("https://example.com")
driver.manage().addCookie(Cookie("test1","cookie1"))
driver.manage().addCookie(Cookie("test2","cookie2"))// Get All available cookiesval cookies = driver.manage().cookies
println(cookies)}finally{
driver.quit()}}
Delete Cookie
Exclui os dados do cookie que correspondem ao nome do cookie fornecido.
driver.get("https://www.selenium.dev/selenium/web/blank.html");
driver.manage().addCookie(newCookie("test1","cookie1"));// delete cookie named
driver.manage().deleteCookieNamed("test1");
// Licensed to the Software Freedom Conservancy (SFC) under one// or more contributor license agreements. See the NOTICE file// distributed with this work for additional information// regarding copyright ownership. The SFC licenses this file// to you under the Apache License, Version 2.0 (the// "License"); you may not use this file except in compliance// with the License. You may obtain a copy of the License at//// http://www.apache.org/licenses/LICENSE-2.0//// Unless required by applicable law or agreed to in writing,// software distributed under the License is distributed on an// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY// KIND, either express or implied. See the License for the// specific language governing permissions and limitations// under the License.importorg.junit.jupiter.api.Test;importorg.junit.jupiter.api.Assertions;importorg.openqa.selenium.Cookie;importorg.openqa.selenium.WebDriver;importorg.openqa.selenium.chrome.ChromeDriver;importjava.util.Set;publicclassCookiesTest{WebDriver driver =newChromeDriver();@TestpublicvoidaddCookie(){
driver.get("https://www.selenium.dev/selenium/web/blank.html");// Add cookie into current browser context
driver.manage().addCookie(newCookie("key","value"));
driver.quit();}@TestpublicvoidgetNamedCookie(){
driver.get("https://www.selenium.dev/selenium/web/blank.html");// Add cookie into current browser context
driver.manage().addCookie(newCookie("foo","bar"));// Get cookie details with named cookie 'foo'Cookie cookie = driver.manage().getCookieNamed("foo");Assertions.assertEquals(cookie.getValue(),"bar");
driver.quit();}@TestpublicvoidgetAllCookies(){
driver.get("https://www.selenium.dev/selenium/web/blank.html");// Add cookies into current browser context
driver.manage().addCookie(newCookie("test1","cookie1"));
driver.manage().addCookie(newCookie("test2","cookie2"));// Get cookiesSet<Cookie> cookies = driver.manage().getCookies();for(Cookie cookie : cookies){if(cookie.getName().equals("test1")){Assertions.assertEquals(cookie.getValue(),"cookie1");}if(cookie.getName().equals("test2")){Assertions.assertEquals(cookie.getValue(),"cookie2");}}
driver.quit();}@TestpublicvoiddeleteCookieNamed(){
driver.get("https://www.selenium.dev/selenium/web/blank.html");
driver.manage().addCookie(newCookie("test1","cookie1"));// delete cookie named
driver.manage().deleteCookieNamed("test1");
driver.quit();}@TestpublicvoiddeleteCookieObject(){
driver.get("https://www.selenium.dev/selenium/web/blank.html");Cookie cookie =newCookie("test2","cookie2");
driver.manage().addCookie(cookie);/*
Selenium Java bindings also provides a way to delete
cookie by passing cookie object of current browsing context
*/
driver.manage().deleteCookie(cookie);
driver.quit();}@TestpublicvoiddeleteAllCookies(){
driver.get("https://www.selenium.dev/selenium/web/blank.html");// Add cookies into current browser context
driver.manage().addCookie(newCookie("test1","cookie1"));
driver.manage().addCookie(newCookie("test2","cookie2"));// Delete All cookies
driver.manage().deleteAllCookies();
driver.quit();}@TestpublicvoidsameSiteCookie(){
driver.get("http://www.example.com");Cookie cookie =newCookie.Builder("key","value").sameSite("Strict").build();Cookie cookie1 =newCookie.Builder("key","value").sameSite("Lax").build();
driver.manage().addCookie(cookie);
driver.manage().addCookie(cookie1);System.out.println(cookie.getSameSite());System.out.println(cookie1.getSameSite());
driver.quit();}}
driver = webdriver.Chrome()
driver.get("http://www.example.com")
driver.add_cookie({"name":"test1","value":"cookie1"})
driver.add_cookie({"name":"test2","value":"cookie2"})# Delete cookie with name 'test1'
driver.delete_cookie("test1")
from selenium import webdriver
deftest_add_cookie():
driver = webdriver.Chrome()
driver.get("http://www.example.com")# Adds the cookie into current browser context
driver.add_cookie({"name":"key","value":"value"})deftest_get_named_cookie():
driver = webdriver.Chrome()
driver.get("http://www.example.com")# Adds the cookie into current browser context
driver.add_cookie({"name":"foo","value":"bar"})# Get cookie details with named cookie 'foo'print(driver.get_cookie("foo"))deftest_get_all_cookies():
driver = webdriver.Chrome()
driver.get("http://www.example.com")
driver.add_cookie({"name":"test1","value":"cookie1"})
driver.add_cookie({"name":"test2","value":"cookie2"})# Get all available cookiesprint(driver.get_cookies())deftest_delete_cookie():
driver = webdriver.Chrome()
driver.get("http://www.example.com")
driver.add_cookie({"name":"test1","value":"cookie1"})
driver.add_cookie({"name":"test2","value":"cookie2"})# Delete cookie with name 'test1'
driver.delete_cookie("test1")deftest_delete_all_cookies():
driver = webdriver.Chrome()
driver.get("http://www.example.com")
driver.add_cookie({"name":"test1","value":"cookie1"})
driver.add_cookie({"name":"test2","value":"cookie2"})# Delete all cookies
driver.delete_all_cookies()deftest_same_side_cookie_attr():
driver = webdriver.Chrome()
driver.get("http://www.example.com")# Adds the cookie into current browser context with sameSite 'Strict' (or) 'Lax'
driver.add_cookie({"name":"foo","value":"value","sameSite":"Strict"})
driver.add_cookie({"name":"foo1","value":"value","sameSite":"Lax"})
cookie1 = driver.get_cookie("foo")
cookie2 = driver.get_cookie("foo1")print(cookie1)print(cookie2)
driver.Url ="https://www.selenium.dev/selenium/web/blank.html";
driver.Manage().Cookies.AddCookie(newCookie("test1","cookie1"));// delete cookie named
driver.Manage().Cookies.DeleteCookieNamed("test1");
// Licensed to the Software Freedom Conservancy (SFC) under one// or more contributor license agreements. See the NOTICE file// distributed with this work for additional information// regarding copyright ownership. The SFC licenses this file// to you under the Apache License, Version 2.0 (the// "License"); you may not use this file except in compliance// with the License. You may obtain a copy of the License at//// http://www.apache.org/licenses/LICENSE-2.0//// Unless required by applicable law or agreed to in writing,// software distributed under the License is distributed on an// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY// KIND, either express or implied. See the License for the// specific language governing permissions and limitations// under the License.usingSystem;usingMicrosoft.VisualStudio.TestTools.UnitTesting;usingOpenQA.Selenium;usingOpenQA.Selenium.Chrome;namespaceSeleniumDocs.Interactions{[TestClass]publicclassCookiesTest{WebDriver driver =newChromeDriver();[TestMethod]publicvoidaddCookie(){
driver.Url="https://www.selenium.dev/selenium/web/blank.html";// Add cookie into current browser context
driver.Manage().Cookies.AddCookie(newCookie("key","value"));
driver.Quit();}[TestMethod]publicvoidgetNamedCookie(){
driver.Url ="https://www.selenium.dev/selenium/web/blank.html";// Add cookie into current browser context
driver.Manage().Cookies.AddCookie(newCookie("foo","bar"));// Get cookie details with named cookie 'foo'Cookie cookie = driver.Manage().Cookies.GetCookieNamed("foo");
Assert.AreEqual(cookie.Value,"bar");
driver.Quit();}[TestMethod]publicvoidgetAllCookies(){
driver.Url ="https://www.selenium.dev/selenium/web/blank.html";// Add cookies into current browser context
driver.Manage().Cookies.AddCookie(newCookie("test1","cookie1"));
driver.Manage().Cookies.AddCookie(newCookie("test2","cookie2"));// Get cookiesvar cookies = driver.Manage().Cookies.AllCookies;foreach(var cookie in cookies){if(cookie.Name.Equals("test1")){
Assert.AreEqual("cookie1", cookie.Value);}if(cookie.Name.Equals("test2")){
Assert.AreEqual("cookie2", cookie.Value);}}
driver.Quit();}[TestMethod]publicvoiddeleteCookieNamed(){
driver.Url ="https://www.selenium.dev/selenium/web/blank.html";
driver.Manage().Cookies.AddCookie(newCookie("test1","cookie1"));// delete cookie named
driver.Manage().Cookies.DeleteCookieNamed("test1");
driver.Quit();}[TestMethod]publicvoiddeleteCookieObject(){
driver.Url ="https://www.selenium.dev/selenium/web/blank.html";Cookie cookie =newCookie("test2","cookie2");
driver.Manage().Cookies.AddCookie(cookie);/*
Selenium CSharp bindings also provides a way to delete
cookie by passing cookie object of current browsing context
*/
driver.Manage().Cookies.DeleteCookie(cookie);
driver.Quit();}[TestMethod]publicvoiddeleteAllCookies(){
driver.Url ="https://www.selenium.dev/selenium/web/blank.html";// Add cookies into current browser context
driver.Manage().Cookies.AddCookie(newCookie("test1","cookie1"));
driver.Manage().Cookies.AddCookie(newCookie("test2","cookie2"));// Delete All cookies
driver.Manage().Cookies.DeleteAllCookies();
driver.Quit();}}}
driver.navigate.to 'https://www.selenium.dev/selenium/web/blank.html'
driver.manage.add_cookie(name:'test1', value:'cookie1')# Delete cookie named
driver.manage.delete_cookie('test1')
# frozen_string_literal: truerequire'spec_helper'RSpec.describe 'Cookies'do
let(:driver){ start_session }
it 'adds a cookie'do
driver.navigate.to 'https://www.selenium.dev/selenium/web/blank.html'# Add cookie into current browser context
driver.manage.add_cookie(name:'key', value:'value')# Verify cookie was added
expect(driver.manage.cookie_named('key')[:value]).to eq('value')end
it 'gets a named cookie'do
driver.navigate.to 'https://www.selenium.dev/selenium/web/blank.html'# Add cookie into current browser context
driver.manage.add_cookie(name:'foo', value:'bar')# Get cookie details with named cookie 'foo'
cookie = driver.manage.cookie_named('foo')
expect(cookie[:value]).to eq('bar')end
it 'gets all cookies'do
driver.navigate.to 'https://www.selenium.dev/selenium/web/blank.html'# Add cookies into current browser context
driver.manage.add_cookie(name:'test1', value:'cookie1')
driver.manage.add_cookie(name:'test2', value:'cookie2')# Get cookies
cookies = driver.manage.all_cookies
# Verify both cookies exist with correct values
test1_cookie = cookies.find {|c| c[:name]=='test1'}
test2_cookie = cookies.find {|c| c[:name]=='test2'}
expect(test1_cookie[:value]).to eq('cookie1')
expect(test2_cookie[:value]).to eq('cookie2')end
it 'deletes a cookie by name'do
driver.navigate.to 'https://www.selenium.dev/selenium/web/blank.html'
driver.manage.add_cookie(name:'test1', value:'cookie1')# Delete cookie named
driver.manage.delete_cookie('test1')# Verify cookie is deleted
expect { driver.manage.cookie_named('test1')}.to raise_error(Selenium::WebDriver::Error::NoSuchCookieError)end
it 'deletes all cookies'do
driver.navigate.to 'https://www.selenium.dev/selenium/web/blank.html'# Add cookies into current browser context
driver.manage.add_cookie(name:'test1', value:'cookie1')
driver.manage.add_cookie(name:'test2', value:'cookie2')# Delete All cookies
driver.manage.delete_all_cookies
# Verify all cookies are deleted
expect(driver.manage.all_cookies.size).to eq(0)endend
const{Browser, Builder}=require("selenium-webdriver");const assert =require('assert')describe('Cookies',function(){let driver;before(asyncfunction(){
driver =newBuilder().forBrowser(Browser.CHROME).build();});after(async()=>await driver.quit());it('Create a cookie',asyncfunction(){await driver.get('https://www.selenium.dev/selenium/web/blank.html');// set a cookie on the current domainawait driver.manage().addCookie({name:'key',value:'value'});});it('Create cookies with sameSite',asyncfunction(){await driver.get('https://www.selenium.dev/selenium/web/blank.html');// set a cookie on the current domain with sameSite 'Strict' (or) 'Lax'await driver.manage().addCookie({name:'key',value:'value',sameSite:'Strict'});await driver.manage().addCookie({name:'key',value:'value',sameSite:'Lax'});});it('Read cookie',asyncfunction(){await driver.get('https://www.selenium.dev/selenium/web/blank.html');// set a cookie on the current domainawait driver.manage().addCookie({name:'foo',value:'bar'});// Get cookie details with named cookie 'foo'await driver.manage().getCookie('foo').then(function(cookie){
assert.equal(cookie.value,'bar');});});it('Read all cookies',asyncfunction(){await driver.get('https://www.selenium.dev/selenium/web/blank.html');// Add few cookiesawait driver.manage().addCookie({name:'test1',value:'cookie1'});await driver.manage().addCookie({name:'test2',value:'cookie2'});// Get all Available cookiesawait driver.manage().getCookies().then(function(cookies){
assert.equal(cookies.filter(cookie=> cookie.name.startsWith('test')).length,2);});});it('Delete a cookie',asyncfunction(){await driver.get('https://www.selenium.dev/selenium/web/blank.html');// Add few cookiesawait driver.manage().addCookie({name:'test1',value:'cookie1'});await driver.manage().addCookie({name:'test2',value:'cookie2'});// Delete a cookie with name 'test1'await driver.manage().deleteCookie('test1');// Get all Available cookiesawait driver.manage().getCookies().then(function(cookies){
assert.equal(cookies.filter(cookie=> cookie.name.startsWith('test')).length,1);});});it('Delete all cookies',asyncfunction(){await driver.get('https://www.selenium.dev/selenium/web/blank.html');// Add few cookiesawait driver.manage().addCookie({name:'test1',value:'cookie1'});await driver.manage().addCookie({name:'test2',value:'cookie2'});// Delete all cookiesawait driver.manage().deleteAllCookies();});});
import org.openqa.selenium.Cookie
import org.openqa.selenium.chrome.ChromeDriver
funmain(){val driver =ChromeDriver()try{
driver.get("https://example.com")
driver.manage().addCookie(Cookie("test1","cookie1"))val cookie1 =Cookie("test2","cookie2")
driver.manage().addCookie(cookie1)// delete a cookie with name 'test1'
driver.manage().deleteCookieNamed("test1")// delete cookie by passing cookie object of current browsing context.
driver.manage().deleteCookie(cookie1)}finally{
driver.quit()}}
Delete All Cookies
Exclui todos os cookies do contexto de navegação atual.
driver.get("https://www.selenium.dev/selenium/web/blank.html");// Add cookies into current browser context
driver.manage().addCookie(newCookie("test1","cookie1"));
driver.manage().addCookie(newCookie("test2","cookie2"));// Delete All cookies
driver.manage().deleteAllCookies();
// Licensed to the Software Freedom Conservancy (SFC) under one// or more contributor license agreements. See the NOTICE file// distributed with this work for additional information// regarding copyright ownership. The SFC licenses this file// to you under the Apache License, Version 2.0 (the// "License"); you may not use this file except in compliance// with the License. You may obtain a copy of the License at//// http://www.apache.org/licenses/LICENSE-2.0//// Unless required by applicable law or agreed to in writing,// software distributed under the License is distributed on an// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY// KIND, either express or implied. See the License for the// specific language governing permissions and limitations// under the License.importorg.junit.jupiter.api.Test;importorg.junit.jupiter.api.Assertions;importorg.openqa.selenium.Cookie;importorg.openqa.selenium.WebDriver;importorg.openqa.selenium.chrome.ChromeDriver;importjava.util.Set;publicclassCookiesTest{WebDriver driver =newChromeDriver();@TestpublicvoidaddCookie(){
driver.get("https://www.selenium.dev/selenium/web/blank.html");// Add cookie into current browser context
driver.manage().addCookie(newCookie("key","value"));
driver.quit();}@TestpublicvoidgetNamedCookie(){
driver.get("https://www.selenium.dev/selenium/web/blank.html");// Add cookie into current browser context
driver.manage().addCookie(newCookie("foo","bar"));// Get cookie details with named cookie 'foo'Cookie cookie = driver.manage().getCookieNamed("foo");Assertions.assertEquals(cookie.getValue(),"bar");
driver.quit();}@TestpublicvoidgetAllCookies(){
driver.get("https://www.selenium.dev/selenium/web/blank.html");// Add cookies into current browser context
driver.manage().addCookie(newCookie("test1","cookie1"));
driver.manage().addCookie(newCookie("test2","cookie2"));// Get cookiesSet<Cookie> cookies = driver.manage().getCookies();for(Cookie cookie : cookies){if(cookie.getName().equals("test1")){Assertions.assertEquals(cookie.getValue(),"cookie1");}if(cookie.getName().equals("test2")){Assertions.assertEquals(cookie.getValue(),"cookie2");}}
driver.quit();}@TestpublicvoiddeleteCookieNamed(){
driver.get("https://www.selenium.dev/selenium/web/blank.html");
driver.manage().addCookie(newCookie("test1","cookie1"));// delete cookie named
driver.manage().deleteCookieNamed("test1");
driver.quit();}@TestpublicvoiddeleteCookieObject(){
driver.get("https://www.selenium.dev/selenium/web/blank.html");Cookie cookie =newCookie("test2","cookie2");
driver.manage().addCookie(cookie);/*
Selenium Java bindings also provides a way to delete
cookie by passing cookie object of current browsing context
*/
driver.manage().deleteCookie(cookie);
driver.quit();}@TestpublicvoiddeleteAllCookies(){
driver.get("https://www.selenium.dev/selenium/web/blank.html");// Add cookies into current browser context
driver.manage().addCookie(newCookie("test1","cookie1"));
driver.manage().addCookie(newCookie("test2","cookie2"));// Delete All cookies
driver.manage().deleteAllCookies();
driver.quit();}@TestpublicvoidsameSiteCookie(){
driver.get("http://www.example.com");Cookie cookie =newCookie.Builder("key","value").sameSite("Strict").build();Cookie cookie1 =newCookie.Builder("key","value").sameSite("Lax").build();
driver.manage().addCookie(cookie);
driver.manage().addCookie(cookie1);System.out.println(cookie.getSameSite());System.out.println(cookie1.getSameSite());
driver.quit();}}
driver = webdriver.Chrome()
driver.get("http://www.example.com")
driver.add_cookie({"name":"test1","value":"cookie1"})
driver.add_cookie({"name":"test2","value":"cookie2"})# Delete all cookies
driver.delete_all_cookies()
from selenium import webdriver
deftest_add_cookie():
driver = webdriver.Chrome()
driver.get("http://www.example.com")# Adds the cookie into current browser context
driver.add_cookie({"name":"key","value":"value"})deftest_get_named_cookie():
driver = webdriver.Chrome()
driver.get("http://www.example.com")# Adds the cookie into current browser context
driver.add_cookie({"name":"foo","value":"bar"})# Get cookie details with named cookie 'foo'print(driver.get_cookie("foo"))deftest_get_all_cookies():
driver = webdriver.Chrome()
driver.get("http://www.example.com")
driver.add_cookie({"name":"test1","value":"cookie1"})
driver.add_cookie({"name":"test2","value":"cookie2"})# Get all available cookiesprint(driver.get_cookies())deftest_delete_cookie():
driver = webdriver.Chrome()
driver.get("http://www.example.com")
driver.add_cookie({"name":"test1","value":"cookie1"})
driver.add_cookie({"name":"test2","value":"cookie2"})# Delete cookie with name 'test1'
driver.delete_cookie("test1")deftest_delete_all_cookies():
driver = webdriver.Chrome()
driver.get("http://www.example.com")
driver.add_cookie({"name":"test1","value":"cookie1"})
driver.add_cookie({"name":"test2","value":"cookie2"})# Delete all cookies
driver.delete_all_cookies()deftest_same_side_cookie_attr():
driver = webdriver.Chrome()
driver.get("http://www.example.com")# Adds the cookie into current browser context with sameSite 'Strict' (or) 'Lax'
driver.add_cookie({"name":"foo","value":"value","sameSite":"Strict"})
driver.add_cookie({"name":"foo1","value":"value","sameSite":"Lax"})
cookie1 = driver.get_cookie("foo")
cookie2 = driver.get_cookie("foo1")print(cookie1)print(cookie2)
driver.Url ="https://www.selenium.dev/selenium/web/blank.html";// Add cookies into current browser context
driver.Manage().Cookies.AddCookie(newCookie("test1","cookie1"));
driver.Manage().Cookies.AddCookie(newCookie("test2","cookie2"));// Delete All cookies
driver.Manage().Cookies.DeleteAllCookies();
// Licensed to the Software Freedom Conservancy (SFC) under one// or more contributor license agreements. See the NOTICE file// distributed with this work for additional information// regarding copyright ownership. The SFC licenses this file// to you under the Apache License, Version 2.0 (the// "License"); you may not use this file except in compliance// with the License. You may obtain a copy of the License at//// http://www.apache.org/licenses/LICENSE-2.0//// Unless required by applicable law or agreed to in writing,// software distributed under the License is distributed on an// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY// KIND, either express or implied. See the License for the// specific language governing permissions and limitations// under the License.usingSystem;usingMicrosoft.VisualStudio.TestTools.UnitTesting;usingOpenQA.Selenium;usingOpenQA.Selenium.Chrome;namespaceSeleniumDocs.Interactions{[TestClass]publicclassCookiesTest{WebDriver driver =newChromeDriver();[TestMethod]publicvoidaddCookie(){
driver.Url="https://www.selenium.dev/selenium/web/blank.html";// Add cookie into current browser context
driver.Manage().Cookies.AddCookie(newCookie("key","value"));
driver.Quit();}[TestMethod]publicvoidgetNamedCookie(){
driver.Url ="https://www.selenium.dev/selenium/web/blank.html";// Add cookie into current browser context
driver.Manage().Cookies.AddCookie(newCookie("foo","bar"));// Get cookie details with named cookie 'foo'Cookie cookie = driver.Manage().Cookies.GetCookieNamed("foo");
Assert.AreEqual(cookie.Value,"bar");
driver.Quit();}[TestMethod]publicvoidgetAllCookies(){
driver.Url ="https://www.selenium.dev/selenium/web/blank.html";// Add cookies into current browser context
driver.Manage().Cookies.AddCookie(newCookie("test1","cookie1"));
driver.Manage().Cookies.AddCookie(newCookie("test2","cookie2"));// Get cookiesvar cookies = driver.Manage().Cookies.AllCookies;foreach(var cookie in cookies){if(cookie.Name.Equals("test1")){
Assert.AreEqual("cookie1", cookie.Value);}if(cookie.Name.Equals("test2")){
Assert.AreEqual("cookie2", cookie.Value);}}
driver.Quit();}[TestMethod]publicvoiddeleteCookieNamed(){
driver.Url ="https://www.selenium.dev/selenium/web/blank.html";
driver.Manage().Cookies.AddCookie(newCookie("test1","cookie1"));// delete cookie named
driver.Manage().Cookies.DeleteCookieNamed("test1");
driver.Quit();}[TestMethod]publicvoiddeleteCookieObject(){
driver.Url ="https://www.selenium.dev/selenium/web/blank.html";Cookie cookie =newCookie("test2","cookie2");
driver.Manage().Cookies.AddCookie(cookie);/*
Selenium CSharp bindings also provides a way to delete
cookie by passing cookie object of current browsing context
*/
driver.Manage().Cookies.DeleteCookie(cookie);
driver.Quit();}[TestMethod]publicvoiddeleteAllCookies(){
driver.Url ="https://www.selenium.dev/selenium/web/blank.html";// Add cookies into current browser context
driver.Manage().Cookies.AddCookie(newCookie("test1","cookie1"));
driver.Manage().Cookies.AddCookie(newCookie("test2","cookie2"));// Delete All cookies
driver.Manage().Cookies.DeleteAllCookies();
driver.Quit();}}}
driver.navigate.to 'https://www.selenium.dev/selenium/web/blank.html'# Add cookies into current browser context
driver.manage.add_cookie(name:'test1', value:'cookie1')
driver.manage.add_cookie(name:'test2', value:'cookie2')# Delete All cookies
driver.manage.delete_all_cookies
# frozen_string_literal: truerequire'spec_helper'RSpec.describe 'Cookies'do
let(:driver){ start_session }
it 'adds a cookie'do
driver.navigate.to 'https://www.selenium.dev/selenium/web/blank.html'# Add cookie into current browser context
driver.manage.add_cookie(name:'key', value:'value')# Verify cookie was added
expect(driver.manage.cookie_named('key')[:value]).to eq('value')end
it 'gets a named cookie'do
driver.navigate.to 'https://www.selenium.dev/selenium/web/blank.html'# Add cookie into current browser context
driver.manage.add_cookie(name:'foo', value:'bar')# Get cookie details with named cookie 'foo'
cookie = driver.manage.cookie_named('foo')
expect(cookie[:value]).to eq('bar')end
it 'gets all cookies'do
driver.navigate.to 'https://www.selenium.dev/selenium/web/blank.html'# Add cookies into current browser context
driver.manage.add_cookie(name:'test1', value:'cookie1')
driver.manage.add_cookie(name:'test2', value:'cookie2')# Get cookies
cookies = driver.manage.all_cookies
# Verify both cookies exist with correct values
test1_cookie = cookies.find {|c| c[:name]=='test1'}
test2_cookie = cookies.find {|c| c[:name]=='test2'}
expect(test1_cookie[:value]).to eq('cookie1')
expect(test2_cookie[:value]).to eq('cookie2')end
it 'deletes a cookie by name'do
driver.navigate.to 'https://www.selenium.dev/selenium/web/blank.html'
driver.manage.add_cookie(name:'test1', value:'cookie1')# Delete cookie named
driver.manage.delete_cookie('test1')# Verify cookie is deleted
expect { driver.manage.cookie_named('test1')}.to raise_error(Selenium::WebDriver::Error::NoSuchCookieError)end
it 'deletes all cookies'do
driver.navigate.to 'https://www.selenium.dev/selenium/web/blank.html'# Add cookies into current browser context
driver.manage.add_cookie(name:'test1', value:'cookie1')
driver.manage.add_cookie(name:'test2', value:'cookie2')# Delete All cookies
driver.manage.delete_all_cookies
# Verify all cookies are deleted
expect(driver.manage.all_cookies.size).to eq(0)endend
const{Browser, Builder}=require("selenium-webdriver");const assert =require('assert')describe('Cookies',function(){let driver;before(asyncfunction(){
driver =newBuilder().forBrowser(Browser.CHROME).build();});after(async()=>await driver.quit());it('Create a cookie',asyncfunction(){await driver.get('https://www.selenium.dev/selenium/web/blank.html');// set a cookie on the current domainawait driver.manage().addCookie({name:'key',value:'value'});});it('Create cookies with sameSite',asyncfunction(){await driver.get('https://www.selenium.dev/selenium/web/blank.html');// set a cookie on the current domain with sameSite 'Strict' (or) 'Lax'await driver.manage().addCookie({name:'key',value:'value',sameSite:'Strict'});await driver.manage().addCookie({name:'key',value:'value',sameSite:'Lax'});});it('Read cookie',asyncfunction(){await driver.get('https://www.selenium.dev/selenium/web/blank.html');// set a cookie on the current domainawait driver.manage().addCookie({name:'foo',value:'bar'});// Get cookie details with named cookie 'foo'await driver.manage().getCookie('foo').then(function(cookie){
assert.equal(cookie.value,'bar');});});it('Read all cookies',asyncfunction(){await driver.get('https://www.selenium.dev/selenium/web/blank.html');// Add few cookiesawait driver.manage().addCookie({name:'test1',value:'cookie1'});await driver.manage().addCookie({name:'test2',value:'cookie2'});// Get all Available cookiesawait driver.manage().getCookies().then(function(cookies){
assert.equal(cookies.filter(cookie=> cookie.name.startsWith('test')).length,2);});});it('Delete a cookie',asyncfunction(){await driver.get('https://www.selenium.dev/selenium/web/blank.html');// Add few cookiesawait driver.manage().addCookie({name:'test1',value:'cookie1'});await driver.manage().addCookie({name:'test2',value:'cookie2'});// Delete a cookie with name 'test1'await driver.manage().deleteCookie('test1');// Get all Available cookiesawait driver.manage().getCookies().then(function(cookies){
assert.equal(cookies.filter(cookie=> cookie.name.startsWith('test')).length,1);});});it('Delete all cookies',asyncfunction(){await driver.get('https://www.selenium.dev/selenium/web/blank.html');// Add few cookiesawait driver.manage().addCookie({name:'test1',value:'cookie1'});await driver.manage().addCookie({name:'test2',value:'cookie2'});// Delete all cookiesawait driver.manage().deleteAllCookies();});});
import org.openqa.selenium.Cookie
import org.openqa.selenium.chrome.ChromeDriver
funmain(){val driver =ChromeDriver()try{
driver.get("https://example.com")
driver.manage().addCookie(Cookie("test1","cookie1"))
driver.manage().addCookie(Cookie("test2","cookie2"))// deletes all cookies
driver.manage().deleteAllCookies()}finally{
driver.quit()}}
Same-Site Cookie Attribute
Permite que um usuário instrua os navegadores a controlar se os cookies
são enviados junto com a solicitação iniciada por sites de terceiros.
É usado para evitar ataques CSRF (Cross-Site Request Forgery).
O atributo de cookie Same-Site aceita dois parâmetros como instruções
Strict:
Quando o atributo sameSite é definido como Strict,
o cookie não será enviado junto com
solicitações iniciadas por sites de terceiros.
Lax:
Quando você define um atributo cookie sameSite como Lax,
o cookie será enviado junto com uma solicitação GET
iniciada por um site de terceiros.
Nota: a partir de agora, esse recurso está disponível no Chrome (versão 80+),
Firefox (versão 79+) e funciona com Selenium 4 e versões posteriores.
// Licensed to the Software Freedom Conservancy (SFC) under one// or more contributor license agreements. See the NOTICE file// distributed with this work for additional information// regarding copyright ownership. The SFC licenses this file// to you under the Apache License, Version 2.0 (the// "License"); you may not use this file except in compliance// with the License. You may obtain a copy of the License at//// http://www.apache.org/licenses/LICENSE-2.0//// Unless required by applicable law or agreed to in writing,// software distributed under the License is distributed on an// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY// KIND, either express or implied. See the License for the// specific language governing permissions and limitations// under the License.importorg.junit.jupiter.api.Test;importorg.junit.jupiter.api.Assertions;importorg.openqa.selenium.Cookie;importorg.openqa.selenium.WebDriver;importorg.openqa.selenium.chrome.ChromeDriver;importjava.util.Set;publicclassCookiesTest{WebDriver driver =newChromeDriver();@TestpublicvoidaddCookie(){
driver.get("https://www.selenium.dev/selenium/web/blank.html");// Add cookie into current browser context
driver.manage().addCookie(newCookie("key","value"));
driver.quit();}@TestpublicvoidgetNamedCookie(){
driver.get("https://www.selenium.dev/selenium/web/blank.html");// Add cookie into current browser context
driver.manage().addCookie(newCookie("foo","bar"));// Get cookie details with named cookie 'foo'Cookie cookie = driver.manage().getCookieNamed("foo");Assertions.assertEquals(cookie.getValue(),"bar");
driver.quit();}@TestpublicvoidgetAllCookies(){
driver.get("https://www.selenium.dev/selenium/web/blank.html");// Add cookies into current browser context
driver.manage().addCookie(newCookie("test1","cookie1"));
driver.manage().addCookie(newCookie("test2","cookie2"));// Get cookiesSet<Cookie> cookies = driver.manage().getCookies();for(Cookie cookie : cookies){if(cookie.getName().equals("test1")){Assertions.assertEquals(cookie.getValue(),"cookie1");}if(cookie.getName().equals("test2")){Assertions.assertEquals(cookie.getValue(),"cookie2");}}
driver.quit();}@TestpublicvoiddeleteCookieNamed(){
driver.get("https://www.selenium.dev/selenium/web/blank.html");
driver.manage().addCookie(newCookie("test1","cookie1"));// delete cookie named
driver.manage().deleteCookieNamed("test1");
driver.quit();}@TestpublicvoiddeleteCookieObject(){
driver.get("https://www.selenium.dev/selenium/web/blank.html");Cookie cookie =newCookie("test2","cookie2");
driver.manage().addCookie(cookie);/*
Selenium Java bindings also provides a way to delete
cookie by passing cookie object of current browsing context
*/
driver.manage().deleteCookie(cookie);
driver.quit();}@TestpublicvoiddeleteAllCookies(){
driver.get("https://www.selenium.dev/selenium/web/blank.html");// Add cookies into current browser context
driver.manage().addCookie(newCookie("test1","cookie1"));
driver.manage().addCookie(newCookie("test2","cookie2"));// Delete All cookies
driver.manage().deleteAllCookies();
driver.quit();}@TestpublicvoidsameSiteCookie(){
driver.get("http://www.example.com");Cookie cookie =newCookie.Builder("key","value").sameSite("Strict").build();Cookie cookie1 =newCookie.Builder("key","value").sameSite("Lax").build();
driver.manage().addCookie(cookie);
driver.manage().addCookie(cookie1);System.out.println(cookie.getSameSite());System.out.println(cookie1.getSameSite());
driver.quit();}}
driver = webdriver.Chrome()
driver.get("http://www.example.com")# Adds the cookie into current browser context with sameSite 'Strict' (or) 'Lax'
driver.add_cookie({"name":"foo","value":"value","sameSite":"Strict"})
driver.add_cookie({"name":"foo1","value":"value","sameSite":"Lax"})
cookie1 = driver.get_cookie("foo")
cookie2 = driver.get_cookie("foo1")print(cookie1)print(cookie2)
from selenium import webdriver
deftest_add_cookie():
driver = webdriver.Chrome()
driver.get("http://www.example.com")# Adds the cookie into current browser context
driver.add_cookie({"name":"key","value":"value"})deftest_get_named_cookie():
driver = webdriver.Chrome()
driver.get("http://www.example.com")# Adds the cookie into current browser context
driver.add_cookie({"name":"foo","value":"bar"})# Get cookie details with named cookie 'foo'print(driver.get_cookie("foo"))deftest_get_all_cookies():
driver = webdriver.Chrome()
driver.get("http://www.example.com")
driver.add_cookie({"name":"test1","value":"cookie1"})
driver.add_cookie({"name":"test2","value":"cookie2"})# Get all available cookiesprint(driver.get_cookies())deftest_delete_cookie():
driver = webdriver.Chrome()
driver.get("http://www.example.com")
driver.add_cookie({"name":"test1","value":"cookie1"})
driver.add_cookie({"name":"test2","value":"cookie2"})# Delete cookie with name 'test1'
driver.delete_cookie("test1")deftest_delete_all_cookies():
driver = webdriver.Chrome()
driver.get("http://www.example.com")
driver.add_cookie({"name":"test1","value":"cookie1"})
driver.add_cookie({"name":"test2","value":"cookie2"})# Delete all cookies
driver.delete_all_cookies()deftest_same_side_cookie_attr():
driver = webdriver.Chrome()
driver.get("http://www.example.com")# Adds the cookie into current browser context with sameSite 'Strict' (or) 'Lax'
driver.add_cookie({"name":"foo","value":"value","sameSite":"Strict"})
driver.add_cookie({"name":"foo1","value":"value","sameSite":"Lax"})
cookie1 = driver.get_cookie("foo")
cookie2 = driver.get_cookie("foo1")print(cookie1)print(cookie2)
const{Browser, Builder}=require("selenium-webdriver");const assert =require('assert')describe('Cookies',function(){let driver;before(asyncfunction(){
driver =newBuilder().forBrowser(Browser.CHROME).build();});after(async()=>await driver.quit());it('Create a cookie',asyncfunction(){await driver.get('https://www.selenium.dev/selenium/web/blank.html');// set a cookie on the current domainawait driver.manage().addCookie({name:'key',value:'value'});});it('Create cookies with sameSite',asyncfunction(){await driver.get('https://www.selenium.dev/selenium/web/blank.html');// set a cookie on the current domain with sameSite 'Strict' (or) 'Lax'await driver.manage().addCookie({name:'key',value:'value',sameSite:'Strict'});await driver.manage().addCookie({name:'key',value:'value',sameSite:'Lax'});});it('Read cookie',asyncfunction(){await driver.get('https://www.selenium.dev/selenium/web/blank.html');// set a cookie on the current domainawait driver.manage().addCookie({name:'foo',value:'bar'});// Get cookie details with named cookie 'foo'await driver.manage().getCookie('foo').then(function(cookie){
assert.equal(cookie.value,'bar');});});it('Read all cookies',asyncfunction(){await driver.get('https://www.selenium.dev/selenium/web/blank.html');// Add few cookiesawait driver.manage().addCookie({name:'test1',value:'cookie1'});await driver.manage().addCookie({name:'test2',value:'cookie2'});// Get all Available cookiesawait driver.manage().getCookies().then(function(cookies){
assert.equal(cookies.filter(cookie=> cookie.name.startsWith('test')).length,2);});});it('Delete a cookie',asyncfunction(){await driver.get('https://www.selenium.dev/selenium/web/blank.html');// Add few cookiesawait driver.manage().addCookie({name:'test1',value:'cookie1'});await driver.manage().addCookie({name:'test2',value:'cookie2'});// Delete a cookie with name 'test1'await driver.manage().deleteCookie('test1');// Get all Available cookiesawait driver.manage().getCookies().then(function(cookies){
assert.equal(cookies.filter(cookie=> cookie.name.startsWith('test')).length,1);});});it('Delete all cookies',asyncfunction(){await driver.get('https://www.selenium.dev/selenium/web/blank.html');// Add few cookiesawait driver.manage().addCookie({name:'test1',value:'cookie1'});await driver.manage().addCookie({name:'test2',value:'cookie2'});// Delete all cookiesawait driver.manage().deleteAllCookies();});});
Frames são um meio obsoleto de construir um layout de site a partir de
vários documentos no mesmo domínio. É improvável que você trabalhe com eles
a menos que você esteja trabalhando com um webapp pré-HTML5. Iframes permitem
a inserção de um documento de um domínio totalmente diferente, e são
ainda comumente usado.
Se você precisa trabalhar com frames ou iframes, o WebDriver permite que você
trabalhe com eles da mesma maneira. Considere um botão dentro de um iframe.
Se inspecionarmos o elemento usando as ferramentas de desenvolvimento do navegador, podemos
ver o seguinte:
Se não fosse pelo iframe, esperaríamos clicar no botão
usando algo como:
//This won't work
driver.findElement(By.tagName("button")).click();
# This Wont work
driver.find_element(By.TAG_NAME,'button').click()
//This won't work
driver.FindElement(By.TagName("button")).Click();
# This won't work
driver.find_element(:tag_name,'button').click
// This won't workawait driver.findElement(By.css('button')).click();
//This won't work
driver.findElement(By.tagName("button")).click()
No entanto, se não houver botões fora do iframe, você pode
em vez disso, obter um erro no such element. Isso acontece porque o Selenium é
ciente apenas dos elementos no documento de nível superior. Para interagir com
o botão, precisamos primeiro mudar para o quadro, de forma semelhante
a como alternamos janelas. WebDriver oferece três maneiras de mudar para
um frame.
Usando um WebElement
Alternar usando um WebElement é a opção mais flexível. Você pode
encontrar o quadro usando seu seletor preferido e mudar para ele.
//switch To IFrame using Web ElementWebElement iframe = driver.findElement(By.id("iframe1"));//Switch to the frame
driver.switchTo().frame(iframe);assertEquals(true, driver.getPageSource().contains("We Leave From Here"));//Now we can type text into email fieldWebElement emailE = driver.findElement(By.id("email"));
emailE.sendKeys("admin@selenium.dev");
emailE.clear();
// Licensed to the Software Freedom Conservancy (SFC) under one// or more contributor license agreements. See the NOTICE file// distributed with this work for additional information// regarding copyright ownership. The SFC licenses this file// to you under the Apache License, Version 2.0 (the// "License"); you may not use this file except in compliance// with the License. You may obtain a copy of the License at//// http://www.apache.org/licenses/LICENSE-2.0//// Unless required by applicable law or agreed to in writing,// software distributed under the License is distributed on an// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY// KIND, either express or implied. See the License for the// specific language governing permissions and limitations// under the License.packagedev.selenium.interactions;importorg.junit.jupiter.api.Test;importorg.openqa.selenium.*;importorg.openqa.selenium.chrome.ChromeDriver;importjava.time.Duration;importstaticorg.junit.jupiter.api.Assertions.assertEquals;publicclassFramesTest{@TestpublicvoidinformationWithElements(){WebDriver driver =newChromeDriver();
driver.manage().timeouts().implicitlyWait(Duration.ofMillis(500));// Navigate to Url
driver.get("https://www.selenium.dev/selenium/web/iframes.html");//switch To IFrame using Web ElementWebElement iframe = driver.findElement(By.id("iframe1"));//Switch to the frame
driver.switchTo().frame(iframe);assertEquals(true, driver.getPageSource().contains("We Leave From Here"));//Now we can type text into email fieldWebElement emailE = driver.findElement(By.id("email"));
emailE.sendKeys("admin@selenium.dev");
emailE.clear();
driver.switchTo().defaultContent();//switch To IFrame using name or id
driver.findElement(By.name("iframe1-name"));//Switch to the frame
driver.switchTo().frame(iframe);assertEquals(true, driver.getPageSource().contains("We Leave From Here"));WebElement email = driver.findElement(By.id("email"));//Now we can type text into email field
email.sendKeys("admin@selenium.dev");
email.clear();
driver.switchTo().defaultContent();//switch To IFrame using index
driver.switchTo().frame(0);assertEquals(true, driver.getPageSource().contains("We Leave From Here"));//leave frame
driver.switchTo().defaultContent();assertEquals(true, driver.getPageSource().contains("This page has iframes"));//quit the browser
driver.quit();}}
# --- Switch to iframe using WebElement ---
iframe = driver.find_element(By.ID,"iframe1")
driver.switch_to.frame(iframe)assert"We Leave From Here"in driver.page_source
email_element = driver.find_element(By.ID,"email")
email_element.send_keys("admin@selenium.dev")
email_element.clear()
driver.switch_to.default_content()
# Licensed to the Software Freedom Conservancy (SFC) under one# or more contributor license agreements. See the NOTICE file# distributed with this work for additional information# regarding copyright ownership. The SFC licenses this file# to you under the Apache License, Version 2.0 (the# "License"); you may not use this file except in compliance# with the License. You may obtain a copy of the License at## http://www.apache.org/licenses/LICENSE-2.0# Unless required by applicable law or agreed to in writing,# software distributed under the License is distributed on an# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY# KIND, either express or implied. See the License for the# specific language governing permissions and limitations# under the License.from selenium import webdriver
from selenium.webdriver.common.by import By
#set chrome and launch web page
driver = webdriver.Chrome()
driver.get("https://www.selenium.dev/selenium/web/iframes.html")# --- Switch to iframe using WebElement ---
iframe = driver.find_element(By.ID,"iframe1")
driver.switch_to.frame(iframe)assert"We Leave From Here"in driver.page_source
email_element = driver.find_element(By.ID,"email")
email_element.send_keys("admin@selenium.dev")
email_element.clear()
driver.switch_to.default_content()# --- Switch to iframe using name or ID ---
iframe1=driver.find_element(By.NAME,"iframe1-name")# (This line doesn't switch, just locates)
driver.switch_to.frame(iframe)assert"We Leave From Here"in driver.page_source
email = driver.find_element(By.ID,"email")
email.send_keys("admin@selenium.dev")
email.clear()
driver.switch_to.default_content()# --- Switch to iframe using index ---
driver.switch_to.frame(0)assert"We Leave From Here"in driver.page_source
# --- Final page content check ---
driver.switch_to.default_content()assert"This page has iframes"in driver.page_source
#quit the driver
driver.quit()#demo code for conference
//switch To IFrame using Web ElementIWebElement iframe = driver.FindElement(By.Id("iframe1"));//Switch to the frame
driver.SwitchTo().Frame(iframe);
Assert.AreEqual(true, driver.PageSource.Contains("We Leave From Here"));//Now we can type text into email fieldIWebElement emailE = driver.FindElement(By.Id("email"));
emailE.SendKeys("admin@selenium.dev");
emailE.Clear();
// Licensed to the Software Freedom Conservancy (SFC) under one// or more contributor license agreements. See the NOTICE file// distributed with this work for additional information// regarding copyright ownership. The SFC licenses this file// to you under the Apache License, Version 2.0 (the// "License"); you may not use this file except in compliance// with the License. You may obtain a copy of the License at//// http://www.apache.org/licenses/LICENSE-2.0//// Unless required by applicable law or agreed to in writing,// software distributed under the License is distributed on an// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY// KIND, either express or implied. See the License for the// specific language governing permissions and limitations// under the License.usingSystem;usingMicrosoft.VisualStudio.TestTools.UnitTesting;usingOpenQA.Selenium;usingOpenQA.Selenium.Chrome;usingSystem.Collections.Generic;namespaceSeleniumDocs.Interactions{[TestClass]publicclassFramesTest{[TestMethod]publicvoidTestFrames(){WebDriver driver =newChromeDriver();
driver.Manage().Timeouts().ImplicitWait = TimeSpan.FromMilliseconds(500);// Navigate to Url
driver.Url="https://www.selenium.dev/selenium/web/iframes.html";//switch To IFrame using Web ElementIWebElement iframe = driver.FindElement(By.Id("iframe1"));//Switch to the frame
driver.SwitchTo().Frame(iframe);
Assert.AreEqual(true, driver.PageSource.Contains("We Leave From Here"));//Now we can type text into email fieldIWebElement emailE = driver.FindElement(By.Id("email"));
emailE.SendKeys("admin@selenium.dev");
emailE.Clear();
driver.SwitchTo().DefaultContent();//switch To IFrame using name or id
driver.FindElement(By.Name("iframe1-name"));//Switch to the frame
driver.SwitchTo().Frame(iframe);
Assert.AreEqual(true, driver.PageSource.Contains("We Leave From Here"));IWebElement email = driver.FindElement(By.Id("email"));//Now we can type text into email field
email.SendKeys("admin@selenium.dev");
email.Clear();
driver.SwitchTo().DefaultContent();//switch To IFrame using index
driver.SwitchTo().Frame(0);
Assert.AreEqual(true, driver.PageSource.Contains("We Leave From Here"));//leave frame
driver.SwitchTo().DefaultContent();
Assert.AreEqual(true, driver.PageSource.Contains("This page has iframes"));//quit the browser
driver.Quit();}}}
# Licensed to the Software Freedom Conservancy (SFC) under one# or more contributor license agreements. See the NOTICE file# distributed with this work for additional information# regarding copyright ownership. The SFC licenses this file# to you under the Apache License, Version 2.0 (the# "License"); you may not use this file except in compliance# with the License. You may obtain a copy of the License at## http://www.apache.org/licenses/LICENSE-2.0# Unless required by applicable law or agreed to in writing,# software distributed under the License is distributed on an# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY# KIND, either express or implied. See the License for the# specific language governing permissions and limitations# under the License.# frozen_string_literal: truerequire'spec_helper'RSpec.describe 'Frames'do
let(:driver){ start_session }
it 'performs iframe switching operations'do
driver.navigate.to 'https://www.selenium.dev/selenium/web/iframes.html'# --- Switch to iframe using WebElement ---
iframe = driver.find_element(:id,'iframe1')
driver.switch_to.frame(iframe)
expect(driver.page_source).to include('We Leave From Here')
email_element = driver.find_element(:id,'email')
email_element.send_keys('admin@selenium.dev')
email_element.clear
driver.switch_to.default_content
# --- Switch to iframe using name or ID ---
iframe1 = driver.find_element(:name,'iframe1-name')
driver.switch_to.frame(iframe1)
expect(driver.page_source).to include('We Leave From Here')
email = driver.find_element(:id,'email')
email.send_keys('admin@selenium.dev')
email.clear
driver.switch_to.default_content
# --- Switch to iframe using index ---
driver.switch_to.frame(0)
expect(driver.page_source).to include('We Leave From Here')# --- Final page content check ---
driver.switch_to.default_content
expect(driver.page_source).to include('This page has iframes')endend
// Store the web elementconst iframe = driver.findElement(By.css('#modal > iframe'));// Switch to the frameawait driver.switchTo().frame(iframe);// Now we can click the buttonawait driver.findElement(By.css('button')).click();
//Store the web elementval iframe = driver.findElement(By.cssSelector("#modal>iframe"))//Switch to the frame
driver.switchTo().frame(iframe)//Now we can click the button
driver.findElement(By.tagName("button")).click()
Usando um name ou ID
Se o seu frame ou iframe tiver um atributo id ou name, ele pode ser
usado alternativamente. Se o name ou ID não for exclusivo na página, o
primeiro encontrado será utilizado.
//switch To IFrame using name or id
driver.findElement(By.name("iframe1-name"));//Switch to the frame
driver.switchTo().frame(iframe);assertEquals(true, driver.getPageSource().contains("We Leave From Here"));WebElement email = driver.findElement(By.id("email"));//Now we can type text into email field
email.sendKeys("admin@selenium.dev");
email.clear();
// Licensed to the Software Freedom Conservancy (SFC) under one// or more contributor license agreements. See the NOTICE file// distributed with this work for additional information// regarding copyright ownership. The SFC licenses this file// to you under the Apache License, Version 2.0 (the// "License"); you may not use this file except in compliance// with the License. You may obtain a copy of the License at//// http://www.apache.org/licenses/LICENSE-2.0//// Unless required by applicable law or agreed to in writing,// software distributed under the License is distributed on an// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY// KIND, either express or implied. See the License for the// specific language governing permissions and limitations// under the License.packagedev.selenium.interactions;importorg.junit.jupiter.api.Test;importorg.openqa.selenium.*;importorg.openqa.selenium.chrome.ChromeDriver;importjava.time.Duration;importstaticorg.junit.jupiter.api.Assertions.assertEquals;publicclassFramesTest{@TestpublicvoidinformationWithElements(){WebDriver driver =newChromeDriver();
driver.manage().timeouts().implicitlyWait(Duration.ofMillis(500));// Navigate to Url
driver.get("https://www.selenium.dev/selenium/web/iframes.html");//switch To IFrame using Web ElementWebElement iframe = driver.findElement(By.id("iframe1"));//Switch to the frame
driver.switchTo().frame(iframe);assertEquals(true, driver.getPageSource().contains("We Leave From Here"));//Now we can type text into email fieldWebElement emailE = driver.findElement(By.id("email"));
emailE.sendKeys("admin@selenium.dev");
emailE.clear();
driver.switchTo().defaultContent();//switch To IFrame using name or id
driver.findElement(By.name("iframe1-name"));//Switch to the frame
driver.switchTo().frame(iframe);assertEquals(true, driver.getPageSource().contains("We Leave From Here"));WebElement email = driver.findElement(By.id("email"));//Now we can type text into email field
email.sendKeys("admin@selenium.dev");
email.clear();
driver.switchTo().defaultContent();//switch To IFrame using index
driver.switchTo().frame(0);assertEquals(true, driver.getPageSource().contains("We Leave From Here"));//leave frame
driver.switchTo().defaultContent();assertEquals(true, driver.getPageSource().contains("This page has iframes"));//quit the browser
driver.quit();}}
# --- Switch to iframe using name or ID ---
iframe1=driver.find_element(By.NAME,"iframe1-name")# (This line doesn't switch, just locates)
driver.switch_to.frame(iframe)assert"We Leave From Here"in driver.page_source
email = driver.find_element(By.ID,"email")
email.send_keys("admin@selenium.dev")
email.clear()
driver.switch_to.default_content()
# Licensed to the Software Freedom Conservancy (SFC) under one# or more contributor license agreements. See the NOTICE file# distributed with this work for additional information# regarding copyright ownership. The SFC licenses this file# to you under the Apache License, Version 2.0 (the# "License"); you may not use this file except in compliance# with the License. You may obtain a copy of the License at## http://www.apache.org/licenses/LICENSE-2.0# Unless required by applicable law or agreed to in writing,# software distributed under the License is distributed on an# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY# KIND, either express or implied. See the License for the# specific language governing permissions and limitations# under the License.from selenium import webdriver
from selenium.webdriver.common.by import By
#set chrome and launch web page
driver = webdriver.Chrome()
driver.get("https://www.selenium.dev/selenium/web/iframes.html")# --- Switch to iframe using WebElement ---
iframe = driver.find_element(By.ID,"iframe1")
driver.switch_to.frame(iframe)assert"We Leave From Here"in driver.page_source
email_element = driver.find_element(By.ID,"email")
email_element.send_keys("admin@selenium.dev")
email_element.clear()
driver.switch_to.default_content()# --- Switch to iframe using name or ID ---
iframe1=driver.find_element(By.NAME,"iframe1-name")# (This line doesn't switch, just locates)
driver.switch_to.frame(iframe)assert"We Leave From Here"in driver.page_source
email = driver.find_element(By.ID,"email")
email.send_keys("admin@selenium.dev")
email.clear()
driver.switch_to.default_content()# --- Switch to iframe using index ---
driver.switch_to.frame(0)assert"We Leave From Here"in driver.page_source
# --- Final page content check ---
driver.switch_to.default_content()assert"This page has iframes"in driver.page_source
#quit the driver
driver.quit()#demo code for conference
//switch To IFrame using name or id
driver.FindElement(By.Name("iframe1-name"));//Switch to the frame
driver.SwitchTo().Frame(iframe);
Assert.AreEqual(true, driver.PageSource.Contains("We Leave From Here"));IWebElement email = driver.FindElement(By.Id("email"));//Now we can type text into email field
email.SendKeys("admin@selenium.dev");
email.Clear();
// Licensed to the Software Freedom Conservancy (SFC) under one// or more contributor license agreements. See the NOTICE file// distributed with this work for additional information// regarding copyright ownership. The SFC licenses this file// to you under the Apache License, Version 2.0 (the// "License"); you may not use this file except in compliance// with the License. You may obtain a copy of the License at//// http://www.apache.org/licenses/LICENSE-2.0//// Unless required by applicable law or agreed to in writing,// software distributed under the License is distributed on an// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY// KIND, either express or implied. See the License for the// specific language governing permissions and limitations// under the License.usingSystem;usingMicrosoft.VisualStudio.TestTools.UnitTesting;usingOpenQA.Selenium;usingOpenQA.Selenium.Chrome;usingSystem.Collections.Generic;namespaceSeleniumDocs.Interactions{[TestClass]publicclassFramesTest{[TestMethod]publicvoidTestFrames(){WebDriver driver =newChromeDriver();
driver.Manage().Timeouts().ImplicitWait = TimeSpan.FromMilliseconds(500);// Navigate to Url
driver.Url="https://www.selenium.dev/selenium/web/iframes.html";//switch To IFrame using Web ElementIWebElement iframe = driver.FindElement(By.Id("iframe1"));//Switch to the frame
driver.SwitchTo().Frame(iframe);
Assert.AreEqual(true, driver.PageSource.Contains("We Leave From Here"));//Now we can type text into email fieldIWebElement emailE = driver.FindElement(By.Id("email"));
emailE.SendKeys("admin@selenium.dev");
emailE.Clear();
driver.SwitchTo().DefaultContent();//switch To IFrame using name or id
driver.FindElement(By.Name("iframe1-name"));//Switch to the frame
driver.SwitchTo().Frame(iframe);
Assert.AreEqual(true, driver.PageSource.Contains("We Leave From Here"));IWebElement email = driver.FindElement(By.Id("email"));//Now we can type text into email field
email.SendKeys("admin@selenium.dev");
email.Clear();
driver.SwitchTo().DefaultContent();//switch To IFrame using index
driver.SwitchTo().Frame(0);
Assert.AreEqual(true, driver.PageSource.Contains("We Leave From Here"));//leave frame
driver.SwitchTo().DefaultContent();
Assert.AreEqual(true, driver.PageSource.Contains("This page has iframes"));//quit the browser
driver.Quit();}}}
# Licensed to the Software Freedom Conservancy (SFC) under one# or more contributor license agreements. See the NOTICE file# distributed with this work for additional information# regarding copyright ownership. The SFC licenses this file# to you under the Apache License, Version 2.0 (the# "License"); you may not use this file except in compliance# with the License. You may obtain a copy of the License at## http://www.apache.org/licenses/LICENSE-2.0# Unless required by applicable law or agreed to in writing,# software distributed under the License is distributed on an# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY# KIND, either express or implied. See the License for the# specific language governing permissions and limitations# under the License.# frozen_string_literal: truerequire'spec_helper'RSpec.describe 'Frames'do
let(:driver){ start_session }
it 'performs iframe switching operations'do
driver.navigate.to 'https://www.selenium.dev/selenium/web/iframes.html'# --- Switch to iframe using WebElement ---
iframe = driver.find_element(:id,'iframe1')
driver.switch_to.frame(iframe)
expect(driver.page_source).to include('We Leave From Here')
email_element = driver.find_element(:id,'email')
email_element.send_keys('admin@selenium.dev')
email_element.clear
driver.switch_to.default_content
# --- Switch to iframe using name or ID ---
iframe1 = driver.find_element(:name,'iframe1-name')
driver.switch_to.frame(iframe1)
expect(driver.page_source).to include('We Leave From Here')
email = driver.find_element(:id,'email')
email.send_keys('admin@selenium.dev')
email.clear
driver.switch_to.default_content
# --- Switch to iframe using index ---
driver.switch_to.frame(0)
expect(driver.page_source).to include('We Leave From Here')# --- Final page content check ---
driver.switch_to.default_content
expect(driver.page_source).to include('This page has iframes')endend
// Using the IDawait driver.switchTo().frame('buttonframe');// Or using the name insteadawait driver.switchTo().frame('myframe');// Now we can click the buttonawait driver.findElement(By.css('button')).click();
//Using the ID
driver.switchTo().frame("buttonframe")//Or using the name instead
driver.switchTo().frame("myframe")//Now we can click the button
driver.findElement(By.tagName("button")).click()
Usando um índice
Também é possível usar o índice do frame, podendo ser
consultado usando window.frames em JavaScript.
//switch To IFrame using index
driver.switchTo().frame(0);
// Licensed to the Software Freedom Conservancy (SFC) under one// or more contributor license agreements. See the NOTICE file// distributed with this work for additional information// regarding copyright ownership. The SFC licenses this file// to you under the Apache License, Version 2.0 (the// "License"); you may not use this file except in compliance// with the License. You may obtain a copy of the License at//// http://www.apache.org/licenses/LICENSE-2.0//// Unless required by applicable law or agreed to in writing,// software distributed under the License is distributed on an// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY// KIND, either express or implied. See the License for the// specific language governing permissions and limitations// under the License.packagedev.selenium.interactions;importorg.junit.jupiter.api.Test;importorg.openqa.selenium.*;importorg.openqa.selenium.chrome.ChromeDriver;importjava.time.Duration;importstaticorg.junit.jupiter.api.Assertions.assertEquals;publicclassFramesTest{@TestpublicvoidinformationWithElements(){WebDriver driver =newChromeDriver();
driver.manage().timeouts().implicitlyWait(Duration.ofMillis(500));// Navigate to Url
driver.get("https://www.selenium.dev/selenium/web/iframes.html");//switch To IFrame using Web ElementWebElement iframe = driver.findElement(By.id("iframe1"));//Switch to the frame
driver.switchTo().frame(iframe);assertEquals(true, driver.getPageSource().contains("We Leave From Here"));//Now we can type text into email fieldWebElement emailE = driver.findElement(By.id("email"));
emailE.sendKeys("admin@selenium.dev");
emailE.clear();
driver.switchTo().defaultContent();//switch To IFrame using name or id
driver.findElement(By.name("iframe1-name"));//Switch to the frame
driver.switchTo().frame(iframe);assertEquals(true, driver.getPageSource().contains("We Leave From Here"));WebElement email = driver.findElement(By.id("email"));//Now we can type text into email field
email.sendKeys("admin@selenium.dev");
email.clear();
driver.switchTo().defaultContent();//switch To IFrame using index
driver.switchTo().frame(0);assertEquals(true, driver.getPageSource().contains("We Leave From Here"));//leave frame
driver.switchTo().defaultContent();assertEquals(true, driver.getPageSource().contains("This page has iframes"));//quit the browser
driver.quit();}}
driver.switch_to.frame(0)assert"We Leave From Here"in driver.page_source
# Licensed to the Software Freedom Conservancy (SFC) under one# or more contributor license agreements. See the NOTICE file# distributed with this work for additional information# regarding copyright ownership. The SFC licenses this file# to you under the Apache License, Version 2.0 (the# "License"); you may not use this file except in compliance# with the License. You may obtain a copy of the License at## http://www.apache.org/licenses/LICENSE-2.0# Unless required by applicable law or agreed to in writing,# software distributed under the License is distributed on an# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY# KIND, either express or implied. See the License for the# specific language governing permissions and limitations# under the License.from selenium import webdriver
from selenium.webdriver.common.by import By
#set chrome and launch web page
driver = webdriver.Chrome()
driver.get("https://www.selenium.dev/selenium/web/iframes.html")# --- Switch to iframe using WebElement ---
iframe = driver.find_element(By.ID,"iframe1")
driver.switch_to.frame(iframe)assert"We Leave From Here"in driver.page_source
email_element = driver.find_element(By.ID,"email")
email_element.send_keys("admin@selenium.dev")
email_element.clear()
driver.switch_to.default_content()# --- Switch to iframe using name or ID ---
iframe1=driver.find_element(By.NAME,"iframe1-name")# (This line doesn't switch, just locates)
driver.switch_to.frame(iframe)assert"We Leave From Here"in driver.page_source
email = driver.find_element(By.ID,"email")
email.send_keys("admin@selenium.dev")
email.clear()
driver.switch_to.default_content()# --- Switch to iframe using index ---
driver.switch_to.frame(0)assert"We Leave From Here"in driver.page_source
# --- Final page content check ---
driver.switch_to.default_content()assert"This page has iframes"in driver.page_source
#quit the driver
driver.quit()#demo code for conference
//switch To IFrame using index
driver.SwitchTo().Frame(0);
// Licensed to the Software Freedom Conservancy (SFC) under one// or more contributor license agreements. See the NOTICE file// distributed with this work for additional information// regarding copyright ownership. The SFC licenses this file// to you under the Apache License, Version 2.0 (the// "License"); you may not use this file except in compliance// with the License. You may obtain a copy of the License at//// http://www.apache.org/licenses/LICENSE-2.0//// Unless required by applicable law or agreed to in writing,// software distributed under the License is distributed on an// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY// KIND, either express or implied. See the License for the// specific language governing permissions and limitations// under the License.usingSystem;usingMicrosoft.VisualStudio.TestTools.UnitTesting;usingOpenQA.Selenium;usingOpenQA.Selenium.Chrome;usingSystem.Collections.Generic;namespaceSeleniumDocs.Interactions{[TestClass]publicclassFramesTest{[TestMethod]publicvoidTestFrames(){WebDriver driver =newChromeDriver();
driver.Manage().Timeouts().ImplicitWait = TimeSpan.FromMilliseconds(500);// Navigate to Url
driver.Url="https://www.selenium.dev/selenium/web/iframes.html";//switch To IFrame using Web ElementIWebElement iframe = driver.FindElement(By.Id("iframe1"));//Switch to the frame
driver.SwitchTo().Frame(iframe);
Assert.AreEqual(true, driver.PageSource.Contains("We Leave From Here"));//Now we can type text into email fieldIWebElement emailE = driver.FindElement(By.Id("email"));
emailE.SendKeys("admin@selenium.dev");
emailE.Clear();
driver.SwitchTo().DefaultContent();//switch To IFrame using name or id
driver.FindElement(By.Name("iframe1-name"));//Switch to the frame
driver.SwitchTo().Frame(iframe);
Assert.AreEqual(true, driver.PageSource.Contains("We Leave From Here"));IWebElement email = driver.FindElement(By.Id("email"));//Now we can type text into email field
email.SendKeys("admin@selenium.dev");
email.Clear();
driver.SwitchTo().DefaultContent();//switch To IFrame using index
driver.SwitchTo().Frame(0);
Assert.AreEqual(true, driver.PageSource.Contains("We Leave From Here"));//leave frame
driver.SwitchTo().DefaultContent();
Assert.AreEqual(true, driver.PageSource.Contains("This page has iframes"));//quit the browser
driver.Quit();}}}
driver.switch_to.frame(0)
expect(driver.page_source).to include('We Leave From Here')
# Licensed to the Software Freedom Conservancy (SFC) under one# or more contributor license agreements. See the NOTICE file# distributed with this work for additional information# regarding copyright ownership. The SFC licenses this file# to you under the Apache License, Version 2.0 (the# "License"); you may not use this file except in compliance# with the License. You may obtain a copy of the License at## http://www.apache.org/licenses/LICENSE-2.0# Unless required by applicable law or agreed to in writing,# software distributed under the License is distributed on an# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY# KIND, either express or implied. See the License for the# specific language governing permissions and limitations# under the License.# frozen_string_literal: truerequire'spec_helper'RSpec.describe 'Frames'do
let(:driver){ start_session }
it 'performs iframe switching operations'do
driver.navigate.to 'https://www.selenium.dev/selenium/web/iframes.html'# --- Switch to iframe using WebElement ---
iframe = driver.find_element(:id,'iframe1')
driver.switch_to.frame(iframe)
expect(driver.page_source).to include('We Leave From Here')
email_element = driver.find_element(:id,'email')
email_element.send_keys('admin@selenium.dev')
email_element.clear
driver.switch_to.default_content
# --- Switch to iframe using name or ID ---
iframe1 = driver.find_element(:name,'iframe1-name')
driver.switch_to.frame(iframe1)
expect(driver.page_source).to include('We Leave From Here')
email = driver.find_element(:id,'email')
email.send_keys('admin@selenium.dev')
email.clear
driver.switch_to.default_content
# --- Switch to iframe using index ---
driver.switch_to.frame(0)
expect(driver.page_source).to include('We Leave From Here')# --- Final page content check ---
driver.switch_to.default_content
expect(driver.page_source).to include('This page has iframes')endend
// Switches to the second frameawait driver.switchTo().frame(1);
// Switches to the second frame
driver.switchTo().frame(1)
Deixando um frame
Para deixar um iframe ou frameset, volte para o conteúdo padrão
como a seguir:
// Licensed to the Software Freedom Conservancy (SFC) under one// or more contributor license agreements. See the NOTICE file// distributed with this work for additional information// regarding copyright ownership. The SFC licenses this file// to you under the Apache License, Version 2.0 (the// "License"); you may not use this file except in compliance// with the License. You may obtain a copy of the License at//// http://www.apache.org/licenses/LICENSE-2.0//// Unless required by applicable law or agreed to in writing,// software distributed under the License is distributed on an// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY// KIND, either express or implied. See the License for the// specific language governing permissions and limitations// under the License.packagedev.selenium.interactions;importorg.junit.jupiter.api.Test;importorg.openqa.selenium.*;importorg.openqa.selenium.chrome.ChromeDriver;importjava.time.Duration;importstaticorg.junit.jupiter.api.Assertions.assertEquals;publicclassFramesTest{@TestpublicvoidinformationWithElements(){WebDriver driver =newChromeDriver();
driver.manage().timeouts().implicitlyWait(Duration.ofMillis(500));// Navigate to Url
driver.get("https://www.selenium.dev/selenium/web/iframes.html");//switch To IFrame using Web ElementWebElement iframe = driver.findElement(By.id("iframe1"));//Switch to the frame
driver.switchTo().frame(iframe);assertEquals(true, driver.getPageSource().contains("We Leave From Here"));//Now we can type text into email fieldWebElement emailE = driver.findElement(By.id("email"));
emailE.sendKeys("admin@selenium.dev");
emailE.clear();
driver.switchTo().defaultContent();//switch To IFrame using name or id
driver.findElement(By.name("iframe1-name"));//Switch to the frame
driver.switchTo().frame(iframe);assertEquals(true, driver.getPageSource().contains("We Leave From Here"));WebElement email = driver.findElement(By.id("email"));//Now we can type text into email field
email.sendKeys("admin@selenium.dev");
email.clear();
driver.switchTo().defaultContent();//switch To IFrame using index
driver.switchTo().frame(0);assertEquals(true, driver.getPageSource().contains("We Leave From Here"));//leave frame
driver.switchTo().defaultContent();assertEquals(true, driver.getPageSource().contains("This page has iframes"));//quit the browser
driver.quit();}}
driver.switch_to.default_content()assert"This page has iframes"in driver.page_source
# Licensed to the Software Freedom Conservancy (SFC) under one# or more contributor license agreements. See the NOTICE file# distributed with this work for additional information# regarding copyright ownership. The SFC licenses this file# to you under the Apache License, Version 2.0 (the# "License"); you may not use this file except in compliance# with the License. You may obtain a copy of the License at## http://www.apache.org/licenses/LICENSE-2.0# Unless required by applicable law or agreed to in writing,# software distributed under the License is distributed on an# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY# KIND, either express or implied. See the License for the# specific language governing permissions and limitations# under the License.from selenium import webdriver
from selenium.webdriver.common.by import By
#set chrome and launch web page
driver = webdriver.Chrome()
driver.get("https://www.selenium.dev/selenium/web/iframes.html")# --- Switch to iframe using WebElement ---
iframe = driver.find_element(By.ID,"iframe1")
driver.switch_to.frame(iframe)assert"We Leave From Here"in driver.page_source
email_element = driver.find_element(By.ID,"email")
email_element.send_keys("admin@selenium.dev")
email_element.clear()
driver.switch_to.default_content()# --- Switch to iframe using name or ID ---
iframe1=driver.find_element(By.NAME,"iframe1-name")# (This line doesn't switch, just locates)
driver.switch_to.frame(iframe)assert"We Leave From Here"in driver.page_source
email = driver.find_element(By.ID,"email")
email.send_keys("admin@selenium.dev")
email.clear()
driver.switch_to.default_content()# --- Switch to iframe using index ---
driver.switch_to.frame(0)assert"We Leave From Here"in driver.page_source
# --- Final page content check ---
driver.switch_to.default_content()assert"This page has iframes"in driver.page_source
#quit the driver
driver.quit()#demo code for conference
// Licensed to the Software Freedom Conservancy (SFC) under one// or more contributor license agreements. See the NOTICE file// distributed with this work for additional information// regarding copyright ownership. The SFC licenses this file// to you under the Apache License, Version 2.0 (the// "License"); you may not use this file except in compliance// with the License. You may obtain a copy of the License at//// http://www.apache.org/licenses/LICENSE-2.0//// Unless required by applicable law or agreed to in writing,// software distributed under the License is distributed on an// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY// KIND, either express or implied. See the License for the// specific language governing permissions and limitations// under the License.usingSystem;usingMicrosoft.VisualStudio.TestTools.UnitTesting;usingOpenQA.Selenium;usingOpenQA.Selenium.Chrome;usingSystem.Collections.Generic;namespaceSeleniumDocs.Interactions{[TestClass]publicclassFramesTest{[TestMethod]publicvoidTestFrames(){WebDriver driver =newChromeDriver();
driver.Manage().Timeouts().ImplicitWait = TimeSpan.FromMilliseconds(500);// Navigate to Url
driver.Url="https://www.selenium.dev/selenium/web/iframes.html";//switch To IFrame using Web ElementIWebElement iframe = driver.FindElement(By.Id("iframe1"));//Switch to the frame
driver.SwitchTo().Frame(iframe);
Assert.AreEqual(true, driver.PageSource.Contains("We Leave From Here"));//Now we can type text into email fieldIWebElement emailE = driver.FindElement(By.Id("email"));
emailE.SendKeys("admin@selenium.dev");
emailE.Clear();
driver.SwitchTo().DefaultContent();//switch To IFrame using name or id
driver.FindElement(By.Name("iframe1-name"));//Switch to the frame
driver.SwitchTo().Frame(iframe);
Assert.AreEqual(true, driver.PageSource.Contains("We Leave From Here"));IWebElement email = driver.FindElement(By.Id("email"));//Now we can type text into email field
email.SendKeys("admin@selenium.dev");
email.Clear();
driver.SwitchTo().DefaultContent();//switch To IFrame using index
driver.SwitchTo().Frame(0);
Assert.AreEqual(true, driver.PageSource.Contains("We Leave From Here"));//leave frame
driver.SwitchTo().DefaultContent();
Assert.AreEqual(true, driver.PageSource.Contains("This page has iframes"));//quit the browser
driver.Quit();}}}
driver.switch_to.default_content
expect(driver.page_source).to include('This page has iframes')
# Licensed to the Software Freedom Conservancy (SFC) under one# or more contributor license agreements. See the NOTICE file# distributed with this work for additional information# regarding copyright ownership. The SFC licenses this file# to you under the Apache License, Version 2.0 (the# "License"); you may not use this file except in compliance# with the License. You may obtain a copy of the License at## http://www.apache.org/licenses/LICENSE-2.0# Unless required by applicable law or agreed to in writing,# software distributed under the License is distributed on an# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY# KIND, either express or implied. See the License for the# specific language governing permissions and limitations# under the License.# frozen_string_literal: truerequire'spec_helper'RSpec.describe 'Frames'do
let(:driver){ start_session }
it 'performs iframe switching operations'do
driver.navigate.to 'https://www.selenium.dev/selenium/web/iframes.html'# --- Switch to iframe using WebElement ---
iframe = driver.find_element(:id,'iframe1')
driver.switch_to.frame(iframe)
expect(driver.page_source).to include('We Leave From Here')
email_element = driver.find_element(:id,'email')
email_element.send_keys('admin@selenium.dev')
email_element.clear
driver.switch_to.default_content
# --- Switch to iframe using name or ID ---
iframe1 = driver.find_element(:name,'iframe1-name')
driver.switch_to.frame(iframe1)
expect(driver.page_source).to include('We Leave From Here')
email = driver.find_element(:id,'email')
email.send_keys('admin@selenium.dev')
email.clear
driver.switch_to.default_content
# --- Switch to iframe using index ---
driver.switch_to.frame(0)
expect(driver.page_source).to include('We Leave From Here')# --- Final page content check ---
driver.switch_to.default_content
expect(driver.page_source).to include('This page has iframes')endend
// Return to the top levelawait driver.switchTo().defaultContent();
// Return to the top level
driver.switchTo().defaultContent()
5 - Print Page
Printing a webpage is a common task, whether for sharing information or maintaining archives.
Selenium simplifies this process through its PrintOptions, PrintsPage, and browsingContext
classes, which provide a flexible and intuitive interface for automating the printing of web pages.
These classes enable you to configure printing preferences, such as page layout, margins, and scaling,
ensuring that the output meets your specific requirements.
Configuring
Orientation
Using the getOrientation() and setOrientation() methods, you can get/set the page orientation — either PORTRAIT or LANDSCAPE.
Using the getPageMargin() and setPageMargin() methods, you can set the margin sizes of the page you wish to print — i.e. top, bottom, left, and right margins.
Once you’ve configured your PrintOptions, you’re ready to print the page. To do this,
you can invoke the print function, which generates a PDF representation of the web page.
The resulting PDF can be saved to your local storage for further use or distribution.
Using PrintsPage(), the print command will return the PDF data in base64-encoded format, which can be decoded
and written to a file in your desired location, and using BrowsingContext() will return a String.
There may currently be multiple implementations depending on your language of choice. For example, with Java you
have the ability to print using either BrowingContext() or PrintsPage(). Both take PrintOptions() objects as a
parameter.
Note: BrowsingContext() is part of Selenium’s BiDi implementation. To enable BiDi see Enabling Bidi
O WebDriver não faz distinção entre janelas e guias. E se
seu site abre uma nova guia ou janela, o Selenium permitirá que você trabalhe
usando um identificador. Cada janela tem um identificador único que permanece
persistente em uma única sessão. Você pode pegar o identificador atual usando:
// Navigate to Url
driver.get("https://www.selenium.dev/selenium/web/window_switching_tests/page_with_frame.html");//fetch handle of thisString currHandle=driver.getWindowHandle();assertNotNull(currHandle);
packagedev.selenium.interactions;importorg.openqa.selenium.*;importorg.openqa.selenium.chrome.ChromeDriver;importjava.time.Duration;importorg.junit.jupiter.api.Test;importstaticorg.junit.jupiter.api.Assertions.*;publicclassWindowsTest{@TestpublicvoidwindowsExampleCode(){WebDriver driver =newChromeDriver();
driver.manage().timeouts().implicitlyWait(Duration.ofMillis(500));// Navigate to Url
driver.get("https://www.selenium.dev/selenium/web/window_switching_tests/page_with_frame.html");//fetch handle of thisString currHandle=driver.getWindowHandle();assertNotNull(currHandle);//click on link to open a new window
driver.findElement(By.linkText("Open new window")).click();//fetch handles of all windows, there will be two, [0]- default, [1] - new windowObject[] windowHandles=driver.getWindowHandles().toArray();
driver.switchTo().window((String) windowHandles[1]);//assert on title of new windowString title=driver.getTitle();assertEquals("Simple Page",title);//closing current window
driver.close();//Switch back to the old tab or window
driver.switchTo().window((String) windowHandles[0]);//Opens a new tab and switches to new tab
driver.switchTo().newWindow(WindowType.TAB);assertEquals("",driver.getTitle());//Opens a new window and switches to new window
driver.switchTo().newWindow(WindowType.WINDOW);assertEquals("",driver.getTitle());//quitting driver
driver.quit();//close all windows}}
driver.current_window_handle
// Navigate to Url
driver.Url="https://www.selenium.dev/selenium/web/window_switching_tests/page_with_frame.html";//fetch handle of thisString currHandle = driver.CurrentWindowHandle;
Assert.IsNotNull(currHandle);
usingSystem;usingMicrosoft.VisualStudio.TestTools.UnitTesting;usingOpenQA.Selenium;usingOpenQA.Selenium.Chrome;usingSystem.Collections.Generic;namespaceSeleniumDocs.Interactions{[TestClass]publicclassWindowsTest{[TestMethod]publicvoidTestWindowCommands(){WebDriver driver =newChromeDriver();
driver.Manage().Timeouts().ImplicitWait = TimeSpan.FromMilliseconds(500);// Navigate to Url
driver.Url="https://www.selenium.dev/selenium/web/window_switching_tests/page_with_frame.html";//fetch handle of thisString currHandle = driver.CurrentWindowHandle;
Assert.IsNotNull(currHandle);//click on link to open a new window
driver.FindElement(By.LinkText("Open new window")).Click();//fetch handles of all windows, there will be two, [0]- default, [1] - new windowIList<string> windowHandles =newList<string>(driver.WindowHandles);
driver.SwitchTo().Window(windowHandles[1]);//assert on title of new windowString title = driver.Title;
Assert.AreEqual("Simple Page", title);//closing current window
driver.Close();//Switch back to the old tab or window
driver.SwitchTo().Window(windowHandles[0]);//Opens a new tab and switches to new tab
driver.SwitchTo().NewWindow(WindowType.Tab);
Assert.AreEqual("", driver.Title);//Opens a new window and switches to new window
driver.SwitchTo().NewWindow(WindowType.Window);
Assert.AreEqual("", driver.Title);//quitting driver
driver.Quit();//close all windows}}}
driver.window_handle
await driver.getWindowHandle();
driver.windowHandle
Alternando janelas ou guias
Clicar em um link que abre em uma
nova janela focará a nova janela ou guia na tela, mas o WebDriver não saberá qual
janela que o sistema operacional considera ativa. Para trabalhar com a nova janela
você precisará mudar para ela. Se você tiver apenas duas guias ou janelas abertas,
e você sabe com qual janela você iniciou, pelo processo de eliminação
você pode percorrer as janelas ou guias que o WebDriver pode ver e alternar
para aquela que não é o original.
No entanto, o Selenium 4 fornece uma nova API NewWindow
que cria uma nova guia (ou) nova janela e muda automaticamente para ela.
//click on link to open a new window
driver.findElement(By.linkText("Open new window")).click();//fetch handles of all windows, there will be two, [0]- default, [1] - new windowObject[] windowHandles=driver.getWindowHandles().toArray();
driver.switchTo().window((String) windowHandles[1]);//assert on title of new windowString title=driver.getTitle();assertEquals("Simple Page",title);
packagedev.selenium.interactions;importorg.openqa.selenium.*;importorg.openqa.selenium.chrome.ChromeDriver;importjava.time.Duration;importorg.junit.jupiter.api.Test;importstaticorg.junit.jupiter.api.Assertions.*;publicclassWindowsTest{@TestpublicvoidwindowsExampleCode(){WebDriver driver =newChromeDriver();
driver.manage().timeouts().implicitlyWait(Duration.ofMillis(500));// Navigate to Url
driver.get("https://www.selenium.dev/selenium/web/window_switching_tests/page_with_frame.html");//fetch handle of thisString currHandle=driver.getWindowHandle();assertNotNull(currHandle);//click on link to open a new window
driver.findElement(By.linkText("Open new window")).click();//fetch handles of all windows, there will be two, [0]- default, [1] - new windowObject[] windowHandles=driver.getWindowHandles().toArray();
driver.switchTo().window((String) windowHandles[1]);//assert on title of new windowString title=driver.getTitle();assertEquals("Simple Page",title);//closing current window
driver.close();//Switch back to the old tab or window
driver.switchTo().window((String) windowHandles[0]);//Opens a new tab and switches to new tab
driver.switchTo().newWindow(WindowType.TAB);assertEquals("",driver.getTitle());//Opens a new window and switches to new window
driver.switchTo().newWindow(WindowType.WINDOW);assertEquals("",driver.getTitle());//quitting driver
driver.quit();//close all windows}}
from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
# Start the driverwith webdriver.Firefox()as driver:# Open URL
driver.get("https://seleniumhq.github.io")# Setup wait for later
wait = WebDriverWait(driver,10)# Store the ID of the original window
original_window = driver.current_window_handle
# Check we don't have other windows open alreadyassertlen(driver.window_handles)==1# Click the link which opens in a new window
driver.find_element(By.LINK_TEXT,"new window").click()# Wait for the new window or tab
wait.until(EC.number_of_windows_to_be(2))# Loop through until we find a new window handlefor window_handle in driver.window_handles:if window_handle != original_window:
driver.switch_to.window(window_handle)break# Wait for the new tab to finish loading content
wait.until(EC.title_is("SeleniumHQ Browser Automation"))
//click on link to open a new window
driver.FindElement(By.LinkText("Open new window")).Click();//fetch handles of all windows, there will be two, [0]- default, [1] - new windowIList<string> windowHandles =newList<string>(driver.WindowHandles);
driver.SwitchTo().Window(windowHandles[1]);//assert on title of new windowString title = driver.Title;
Assert.AreEqual("Simple Page", title);
usingSystem;usingMicrosoft.VisualStudio.TestTools.UnitTesting;usingOpenQA.Selenium;usingOpenQA.Selenium.Chrome;usingSystem.Collections.Generic;namespaceSeleniumDocs.Interactions{[TestClass]publicclassWindowsTest{[TestMethod]publicvoidTestWindowCommands(){WebDriver driver =newChromeDriver();
driver.Manage().Timeouts().ImplicitWait = TimeSpan.FromMilliseconds(500);// Navigate to Url
driver.Url="https://www.selenium.dev/selenium/web/window_switching_tests/page_with_frame.html";//fetch handle of thisString currHandle = driver.CurrentWindowHandle;
Assert.IsNotNull(currHandle);//click on link to open a new window
driver.FindElement(By.LinkText("Open new window")).Click();//fetch handles of all windows, there will be two, [0]- default, [1] - new windowIList<string> windowHandles =newList<string>(driver.WindowHandles);
driver.SwitchTo().Window(windowHandles[1]);//assert on title of new windowString title = driver.Title;
Assert.AreEqual("Simple Page", title);//closing current window
driver.Close();//Switch back to the old tab or window
driver.SwitchTo().Window(windowHandles[0]);//Opens a new tab and switches to new tab
driver.SwitchTo().NewWindow(WindowType.Tab);
Assert.AreEqual("", driver.Title);//Opens a new window and switches to new window
driver.SwitchTo().NewWindow(WindowType.Window);
Assert.AreEqual("", driver.Title);//quitting driver
driver.Quit();//close all windows}}}
#Store the ID of the original window
original_window = driver.window_handle
#Check we don't have other windows open already
assert(driver.window_handles.length ==1,'Expected one window')#Click the link which opens in a new window
driver.find_element(link:'new window').click
#Wait for the new window or tab
wait.until{ driver.window_handles.length ==2}#Loop through until we find a new window handle
driver.window_handles.eachdo|handle|if handle != original_window
driver.switch_to.window handle
breakendend#Wait for the new tab to finish loading content
wait.until{ driver.title =='Selenium documentation'}
//Store the ID of the original windowconst originalWindow =await driver.getWindowHandle();//Check we don't have other windows open alreadyassert((await driver.getAllWindowHandles()).length ===1);//Click the link which opens in a new windowawait driver.findElement(By.linkText('new window')).click();//Wait for the new window or tabawait driver.wait(async()=>(await driver.getAllWindowHandles()).length ===2,10000);//Loop through until we find a new window handleconst windows =await driver.getAllWindowHandles();
windows.forEach(asynchandle=>{if(handle !== originalWindow){await driver.switchTo().window(handle);}});//Wait for the new tab to finish loading contentawait driver.wait(until.titleIs('Selenium documentation'),10000);
//Store the ID of the original windowval originalWindow = driver.getWindowHandle()//Check we don't have other windows open alreadyassert(driver.getWindowHandles().size()===1)//Click the link which opens in a new window
driver.findElement(By.linkText("new window")).click()//Wait for the new window or tab
wait.until(numberOfWindowsToBe(2))//Loop through until we find a new window handlefor(windowHandle in driver.getWindowHandles()){if(!originalWindow.contentEquals(windowHandle)){
driver.switchTo().window(windowHandle)break}}//Wait for the new tab to finish loading content
wait.until(titleIs("Selenium documentation"))
Fechando uma janela ou guia
Quando você fechar uma janela ou guia e que não é a
última janela ou guia aberta em seu navegador, você deve fechá-la e alternar
de volta para a janela que você estava usando anteriormente. Supondo que você seguiu a
amostra de código na seção anterior, você terá o identificador da janela
anterior armazenado em uma variável. Junte isso e você obterá:
//closing current window
driver.close();//Switch back to the old tab or window
driver.switchTo().window((String) windowHandles[0]);
packagedev.selenium.interactions;importorg.openqa.selenium.*;importorg.openqa.selenium.chrome.ChromeDriver;importjava.time.Duration;importorg.junit.jupiter.api.Test;importstaticorg.junit.jupiter.api.Assertions.*;publicclassWindowsTest{@TestpublicvoidwindowsExampleCode(){WebDriver driver =newChromeDriver();
driver.manage().timeouts().implicitlyWait(Duration.ofMillis(500));// Navigate to Url
driver.get("https://www.selenium.dev/selenium/web/window_switching_tests/page_with_frame.html");//fetch handle of thisString currHandle=driver.getWindowHandle();assertNotNull(currHandle);//click on link to open a new window
driver.findElement(By.linkText("Open new window")).click();//fetch handles of all windows, there will be two, [0]- default, [1] - new windowObject[] windowHandles=driver.getWindowHandles().toArray();
driver.switchTo().window((String) windowHandles[1]);//assert on title of new windowString title=driver.getTitle();assertEquals("Simple Page",title);//closing current window
driver.close();//Switch back to the old tab or window
driver.switchTo().window((String) windowHandles[0]);//Opens a new tab and switches to new tab
driver.switchTo().newWindow(WindowType.TAB);assertEquals("",driver.getTitle());//Opens a new window and switches to new window
driver.switchTo().newWindow(WindowType.WINDOW);assertEquals("",driver.getTitle());//quitting driver
driver.quit();//close all windows}}
#Close the tab or window
driver.close()#Switch back to the old tab or window
driver.switch_to.window(original_window)
//closing current window
driver.Close();//Switch back to the old tab or window
driver.SwitchTo().Window(windowHandles[0]);
usingSystem;usingMicrosoft.VisualStudio.TestTools.UnitTesting;usingOpenQA.Selenium;usingOpenQA.Selenium.Chrome;usingSystem.Collections.Generic;namespaceSeleniumDocs.Interactions{[TestClass]publicclassWindowsTest{[TestMethod]publicvoidTestWindowCommands(){WebDriver driver =newChromeDriver();
driver.Manage().Timeouts().ImplicitWait = TimeSpan.FromMilliseconds(500);// Navigate to Url
driver.Url="https://www.selenium.dev/selenium/web/window_switching_tests/page_with_frame.html";//fetch handle of thisString currHandle = driver.CurrentWindowHandle;
Assert.IsNotNull(currHandle);//click on link to open a new window
driver.FindElement(By.LinkText("Open new window")).Click();//fetch handles of all windows, there will be two, [0]- default, [1] - new windowIList<string> windowHandles =newList<string>(driver.WindowHandles);
driver.SwitchTo().Window(windowHandles[1]);//assert on title of new windowString title = driver.Title;
Assert.AreEqual("Simple Page", title);//closing current window
driver.Close();//Switch back to the old tab or window
driver.SwitchTo().Window(windowHandles[0]);//Opens a new tab and switches to new tab
driver.SwitchTo().NewWindow(WindowType.Tab);
Assert.AreEqual("", driver.Title);//Opens a new window and switches to new window
driver.SwitchTo().NewWindow(WindowType.Window);
Assert.AreEqual("", driver.Title);//quitting driver
driver.Quit();//close all windows}}}
#Close the tab or window
driver.close
#Switch back to the old tab or window
driver.switch_to.window original_window
//Close the tab or windowawait driver.close();//Switch back to the old tab or windowawait driver.switchTo().window(originalWindow);
//Close the tab or window
driver.close()//Switch back to the old tab or window
driver.switchTo().window(originalWindow)
Esquecer de voltar para outro gerenciador de janela após fechar uma
janela deixará o WebDriver em execução na página agora fechada e
acionara uma No Such Window Exception. Você deve trocar
de volta para um identificador de janela válido para continuar a execução.
Criar nova janela (ou) nova guia e alternar
Cria uma nova janela (ou) guia e focará a nova janela ou guia na tela.
Você não precisa mudar para trabalhar com a nova janela (ou) guia. Se você tiver mais de duas janelas
(ou) guias abertas diferentes da nova janela, você pode percorrer as janelas ou guias que o WebDriver pode ver
e mudar para aquela que não é a original.
Nota: este recurso funciona com Selenium 4 e versões posteriores.
//Opens a new tab and switches to new tab
driver.switchTo().newWindow(WindowType.TAB);assertEquals("",driver.getTitle());//Opens a new window and switches to new window
driver.switchTo().newWindow(WindowType.WINDOW);assertEquals("",driver.getTitle());
packagedev.selenium.interactions;importorg.openqa.selenium.*;importorg.openqa.selenium.chrome.ChromeDriver;importjava.time.Duration;importorg.junit.jupiter.api.Test;importstaticorg.junit.jupiter.api.Assertions.*;publicclassWindowsTest{@TestpublicvoidwindowsExampleCode(){WebDriver driver =newChromeDriver();
driver.manage().timeouts().implicitlyWait(Duration.ofMillis(500));// Navigate to Url
driver.get("https://www.selenium.dev/selenium/web/window_switching_tests/page_with_frame.html");//fetch handle of thisString currHandle=driver.getWindowHandle();assertNotNull(currHandle);//click on link to open a new window
driver.findElement(By.linkText("Open new window")).click();//fetch handles of all windows, there will be two, [0]- default, [1] - new windowObject[] windowHandles=driver.getWindowHandles().toArray();
driver.switchTo().window((String) windowHandles[1]);//assert on title of new windowString title=driver.getTitle();assertEquals("Simple Page",title);//closing current window
driver.close();//Switch back to the old tab or window
driver.switchTo().window((String) windowHandles[0]);//Opens a new tab and switches to new tab
driver.switchTo().newWindow(WindowType.TAB);assertEquals("",driver.getTitle());//Opens a new window and switches to new window
driver.switchTo().newWindow(WindowType.WINDOW);assertEquals("",driver.getTitle());//quitting driver
driver.quit();//close all windows}}
# Opens a new tab and switches to new tab
driver.switch_to.new_window('tab')# Opens a new window and switches to new window
driver.switch_to.new_window('window')
//Opens a new tab and switches to new tab
driver.SwitchTo().NewWindow(WindowType.Tab);
Assert.AreEqual("", driver.Title);//Opens a new window and switches to new window
driver.SwitchTo().NewWindow(WindowType.Window);
Assert.AreEqual("", driver.Title);
usingSystem;usingMicrosoft.VisualStudio.TestTools.UnitTesting;usingOpenQA.Selenium;usingOpenQA.Selenium.Chrome;usingSystem.Collections.Generic;namespaceSeleniumDocs.Interactions{[TestClass]publicclassWindowsTest{[TestMethod]publicvoidTestWindowCommands(){WebDriver driver =newChromeDriver();
driver.Manage().Timeouts().ImplicitWait = TimeSpan.FromMilliseconds(500);// Navigate to Url
driver.Url="https://www.selenium.dev/selenium/web/window_switching_tests/page_with_frame.html";//fetch handle of thisString currHandle = driver.CurrentWindowHandle;
Assert.IsNotNull(currHandle);//click on link to open a new window
driver.FindElement(By.LinkText("Open new window")).Click();//fetch handles of all windows, there will be two, [0]- default, [1] - new windowIList<string> windowHandles =newList<string>(driver.WindowHandles);
driver.SwitchTo().Window(windowHandles[1]);//assert on title of new windowString title = driver.Title;
Assert.AreEqual("Simple Page", title);//closing current window
driver.Close();//Switch back to the old tab or window
driver.SwitchTo().Window(windowHandles[0]);//Opens a new tab and switches to new tab
driver.SwitchTo().NewWindow(WindowType.Tab);
Assert.AreEqual("", driver.Title);//Opens a new window and switches to new window
driver.SwitchTo().NewWindow(WindowType.Window);
Assert.AreEqual("", driver.Title);//quitting driver
driver.Quit();//close all windows}}}
const{Builder, By}=require('selenium-webdriver');const chrome =require('selenium-webdriver/chrome');const assert =require("node:assert");let opts =newchrome.Options();
opts.addArguments('--headless');let startIndex =0let endIndex =5let pdfMagicNumber ='JVBER'let imgMagicNumber ='iVBOR'let base64Code
describe('Interactions - Windows',function(){let driver;before(asyncfunction(){
driver =awaitnewBuilder().forBrowser('chrome').setChromeOptions(opts).build();});after(async()=>await driver.quit());it('Should be able to print page to pdf',asyncfunction(){await driver.get('https://www.selenium.dev/selenium/web/alerts.html');let base64 =await driver.printPage({pageRanges:["1-2"]});// page can be saved as a PDF as below// await fs.writeFileSync('./test.pdf', base64, 'base64');
base64Code = base64.slice(startIndex, endIndex)
assert.strictEqual(base64Code, pdfMagicNumber)});it('Should be able to get text using executeScript',asyncfunction(){await driver.get('https://www.selenium.dev/selenium/web/javascriptPage.html');// Stores the header elementlet header =await driver.findElement(By.css('h1'));// Executing JavaScript to capture innerText of header elementlet text =await driver.executeScript('return arguments[0].innerText', header);
assert.strictEqual(text,`Type Stuff`)});it('Should be able to take Element Screenshot',asyncfunction(){await driver.get('https://www.selenium.dev/selenium/web/javascriptPage.html');let header =await driver.findElement(By.css('h1'));// Captures the element screenshotlet encodedString =await header.takeScreenshot(true);// save screenshot as below// await fs.writeFileSync('./image.png', encodedString, 'base64');
base64Code = encodedString.slice(startIndex, endIndex)
assert.strictEqual(base64Code, imgMagicNumber)});it('Should be able to takeScreenshot',asyncfunction(){await driver.get('https://www.selenium.dev/selenium/web/javascriptPage.html');// Captures the screenshotlet encodedString =await driver.takeScreenshot();// save screenshot as below// await fs.writeFileSync('./image.png', encodedString, 'base64');
base64Code = encodedString.slice(startIndex, endIndex)
assert.strictEqual(base64Code, imgMagicNumber)});it('Should be able to switch to newWindow and newTab and close',asyncfunction(){await driver.get('https://www.selenium.dev/selenium/web/');const initialWindow =await driver.getAllWindowHandles();
assert.strictEqual(initialWindow.length,1)// Opens a new tab and switches to new tabawait driver.switchTo().newWindow('tab');const browserTabs =await driver.getAllWindowHandles();
assert.strictEqual(browserTabs.length,2)// Opens a new window and switches to new windowawait driver.switchTo().newWindow('window');const windows =await driver.getAllWindowHandles();
assert.strictEqual(windows.length,3)//Close the tab or windowawait driver.close();//Switch back to the old tab or windowawait driver.switchTo().window(windows[1]);const windowsAfterClose =await driver.getAllWindowHandles();
assert.strictEqual(windowsAfterClose.length,2);});it('Should be able to getWindow Size',asyncfunction(){await driver.get('https://www.selenium.dev/selenium/web/');// Access each dimension individuallyconst{ width, height }=await driver.manage().window().getRect();// Or store the dimensions and query them laterconst rect =await driver.manage().window().getRect();const windowWidth = rect.width;const windowHeight = rect.height;
assert.ok(windowWidth>0);
assert.ok(windowHeight>0);});it('Should be able to getWindow position',asyncfunction(){await driver.get('https://www.selenium.dev/selenium/web/');// Access each dimension individuallyconst{ x, y }=await driver.manage().window().getRect();// Or store the dimensions and query them laterconst rect =await driver.manage().window().getRect();const x1 = rect.x;const y1 = rect.y;
assert.ok(x1>=0);
assert.ok(y1>=0);});});
const{Builder, By}=require('selenium-webdriver');const chrome =require('selenium-webdriver/chrome');const assert =require("node:assert");let opts =newchrome.Options();
opts.addArguments('--headless');let startIndex =0let endIndex =5let pdfMagicNumber ='JVBER'let imgMagicNumber ='iVBOR'let base64Code
describe('Interactions - Windows',function(){let driver;before(asyncfunction(){
driver =awaitnewBuilder().forBrowser('chrome').setChromeOptions(opts).build();});after(async()=>await driver.quit());it('Should be able to print page to pdf',asyncfunction(){await driver.get('https://www.selenium.dev/selenium/web/alerts.html');let base64 =await driver.printPage({pageRanges:["1-2"]});// page can be saved as a PDF as below// await fs.writeFileSync('./test.pdf', base64, 'base64');
base64Code = base64.slice(startIndex, endIndex)
assert.strictEqual(base64Code, pdfMagicNumber)});it('Should be able to get text using executeScript',asyncfunction(){await driver.get('https://www.selenium.dev/selenium/web/javascriptPage.html');// Stores the header elementlet header =await driver.findElement(By.css('h1'));// Executing JavaScript to capture innerText of header elementlet text =await driver.executeScript('return arguments[0].innerText', header);
assert.strictEqual(text,`Type Stuff`)});it('Should be able to take Element Screenshot',asyncfunction(){await driver.get('https://www.selenium.dev/selenium/web/javascriptPage.html');let header =await driver.findElement(By.css('h1'));// Captures the element screenshotlet encodedString =await header.takeScreenshot(true);// save screenshot as below// await fs.writeFileSync('./image.png', encodedString, 'base64');
base64Code = encodedString.slice(startIndex, endIndex)
assert.strictEqual(base64Code, imgMagicNumber)});it('Should be able to takeScreenshot',asyncfunction(){await driver.get('https://www.selenium.dev/selenium/web/javascriptPage.html');// Captures the screenshotlet encodedString =await driver.takeScreenshot();// save screenshot as below// await fs.writeFileSync('./image.png', encodedString, 'base64');
base64Code = encodedString.slice(startIndex, endIndex)
assert.strictEqual(base64Code, imgMagicNumber)});it('Should be able to switch to newWindow and newTab and close',asyncfunction(){await driver.get('https://www.selenium.dev/selenium/web/');const initialWindow =await driver.getAllWindowHandles();
assert.strictEqual(initialWindow.length,1)// Opens a new tab and switches to new tabawait driver.switchTo().newWindow('tab');const browserTabs =await driver.getAllWindowHandles();
assert.strictEqual(browserTabs.length,2)// Opens a new window and switches to new windowawait driver.switchTo().newWindow('window');const windows =await driver.getAllWindowHandles();
assert.strictEqual(windows.length,3)//Close the tab or windowawait driver.close();//Switch back to the old tab or windowawait driver.switchTo().window(windows[1]);const windowsAfterClose =await driver.getAllWindowHandles();
assert.strictEqual(windowsAfterClose.length,2);});it('Should be able to getWindow Size',asyncfunction(){await driver.get('https://www.selenium.dev/selenium/web/');// Access each dimension individuallyconst{ width, height }=await driver.manage().window().getRect();// Or store the dimensions and query them laterconst rect =await driver.manage().window().getRect();const windowWidth = rect.width;const windowHeight = rect.height;
assert.ok(windowWidth>0);
assert.ok(windowHeight>0);});it('Should be able to getWindow position',asyncfunction(){await driver.get('https://www.selenium.dev/selenium/web/');// Access each dimension individuallyconst{ x, y }=await driver.manage().window().getRect();// Or store the dimensions and query them laterconst rect =await driver.manage().window().getRect();const x1 = rect.x;const y1 = rect.y;
assert.ok(x1>=0);
assert.ok(y1>=0);});});
// Opens a new tab and switches to new tab
driver.switchTo().newWindow(WindowType.TAB)// Opens a new window and switches to new window
driver.switchTo().newWindow(WindowType.WINDOW)
Sair do navegador no final de uma sessão
Quando você terminar a sessão do navegador, você deve chamar a função quit(),
em vez de fechar:
//quitting driver
driver.quit();//close all windows
packagedev.selenium.interactions;importorg.openqa.selenium.*;importorg.openqa.selenium.chrome.ChromeDriver;importjava.time.Duration;importorg.junit.jupiter.api.Test;importstaticorg.junit.jupiter.api.Assertions.*;publicclassWindowsTest{@TestpublicvoidwindowsExampleCode(){WebDriver driver =newChromeDriver();
driver.manage().timeouts().implicitlyWait(Duration.ofMillis(500));// Navigate to Url
driver.get("https://www.selenium.dev/selenium/web/window_switching_tests/page_with_frame.html");//fetch handle of thisString currHandle=driver.getWindowHandle();assertNotNull(currHandle);//click on link to open a new window
driver.findElement(By.linkText("Open new window")).click();//fetch handles of all windows, there will be two, [0]- default, [1] - new windowObject[] windowHandles=driver.getWindowHandles().toArray();
driver.switchTo().window((String) windowHandles[1]);//assert on title of new windowString title=driver.getTitle();assertEquals("Simple Page",title);//closing current window
driver.close();//Switch back to the old tab or window
driver.switchTo().window((String) windowHandles[0]);//Opens a new tab and switches to new tab
driver.switchTo().newWindow(WindowType.TAB);assertEquals("",driver.getTitle());//Opens a new window and switches to new window
driver.switchTo().newWindow(WindowType.WINDOW);assertEquals("",driver.getTitle());//quitting driver
driver.quit();//close all windows}}
driver.quit()
//quitting driver
driver.Quit();//close all windows
usingSystem;usingMicrosoft.VisualStudio.TestTools.UnitTesting;usingOpenQA.Selenium;usingOpenQA.Selenium.Chrome;usingSystem.Collections.Generic;namespaceSeleniumDocs.Interactions{[TestClass]publicclassWindowsTest{[TestMethod]publicvoidTestWindowCommands(){WebDriver driver =newChromeDriver();
driver.Manage().Timeouts().ImplicitWait = TimeSpan.FromMilliseconds(500);// Navigate to Url
driver.Url="https://www.selenium.dev/selenium/web/window_switching_tests/page_with_frame.html";//fetch handle of thisString currHandle = driver.CurrentWindowHandle;
Assert.IsNotNull(currHandle);//click on link to open a new window
driver.FindElement(By.LinkText("Open new window")).Click();//fetch handles of all windows, there will be two, [0]- default, [1] - new windowIList<string> windowHandles =newList<string>(driver.WindowHandles);
driver.SwitchTo().Window(windowHandles[1]);//assert on title of new windowString title = driver.Title;
Assert.AreEqual("Simple Page", title);//closing current window
driver.Close();//Switch back to the old tab or window
driver.SwitchTo().Window(windowHandles[0]);//Opens a new tab and switches to new tab
driver.SwitchTo().NewWindow(WindowType.Tab);
Assert.AreEqual("", driver.Title);//Opens a new window and switches to new window
driver.SwitchTo().NewWindow(WindowType.Window);
Assert.AreEqual("", driver.Title);//quitting driver
driver.Quit();//close all windows}}}
driver.quit
await driver.quit();
driver.quit()
quit() irá:
Fechar todas as janelas e guias associadas a essa sessão do WebDriver
Fechar o processo do navegador
Fechar o processo do driver em segundo plano
Notificar o Selenium Grid de que o navegador não está mais em uso para que possa
ser usado por outra sessão (se você estiver usando Selenium Grid)
A falha em encerrar deixará processos e portas extras em segundo plano
rodando em sua máquina, o que pode causar problemas mais tarde.
Algumas estruturas de teste oferecem métodos e anotações em que você pode ligar para derrubar no final de um teste.
/**
* Example using JUnit
* https://junit.org/junit5/docs/current/api/org/junit/jupiter/api/AfterAll.html
*/@AfterAllpublicstaticvoidtearDown(){
driver.quit();}
/*
Example using Visual Studio's UnitTesting
https://msdn.microsoft.com/en-us/library/microsoft.visualstudio.testtools.unittesting.aspx
*/[TestCleanup]publicvoidTearDown(){
driver.Quit();}
# UnitTest Teardown# https://www.rubydoc.info/github/test-unit/test-unit/Test/Unit/TestCasedefteardown@driver.quit
end
/**
* Example using Mocha
* https://mochajs.org/#hooks
*/after('Tear down',asyncfunction(){await driver.quit();});
/**
* Example using JUnit
* https://junit.org/junit5/docs/current/api/org/junit/jupiter/api/AfterAll.html
*/@AfterAllfuntearDown(){
driver.quit()}
Se não estiver executando o WebDriver em um contexto de teste, você pode considerar o uso do
try/finally que é oferecido pela maioria das linguagens para que uma exceção
ainda limpe a sessão do WebDriver.
O WebDriver do Python agora suporta o gerenciador de contexto python,
que ao usar a palavra-chave with pode encerrar automaticamente o
driver no fim da execução.
with webdriver.Firefox()as driver:# WebDriver code here...# WebDriver will automatically quit after indentation
Gerenciamento de janelas
A resolução da tela pode impactar como seu aplicativo da web é renderizado, então
WebDriver fornece mecanismos para mover e redimensionar a janela do navegador.
Coletar o tamanho da janela
Obtém o tamanho da janela do navegador em pixels.
//Access each dimension individuallyint width = driver.manage().window().getSize().getWidth();int height = driver.manage().window().getSize().getHeight();//Or store the dimensions and query them laterDimension size = driver.manage().window().getSize();int width1 = size.getWidth();int height1 = size.getHeight();
# Access each dimension individually
width = driver.get_window_size().get("width")
height = driver.get_window_size().get("height")# Or store the dimensions and query them later
size = driver.get_window_size()
width1 = size.get("width")
height1 = size.get("height")
//Access each dimension individuallyint width = driver.Manage().Window.Size.Width;int height = driver.Manage().Window.Size.Height;//Or store the dimensions and query them laterSystem.Drawing.Size size = driver.Manage().Window.Size;int width1 = size.Width;int height1 = size.Height;
# Access each dimension individually
width = driver.manage.window.size.width
height = driver.manage.window.size.height
# Or store the dimensions and query them later
size = driver.manage.window.size
width1 = size.width
height1 = size.height
const{Builder, By}=require('selenium-webdriver');const chrome =require('selenium-webdriver/chrome');const assert =require("node:assert");let opts =newchrome.Options();
opts.addArguments('--headless');let startIndex =0let endIndex =5let pdfMagicNumber ='JVBER'let imgMagicNumber ='iVBOR'let base64Code
describe('Interactions - Windows',function(){let driver;before(asyncfunction(){
driver =awaitnewBuilder().forBrowser('chrome').setChromeOptions(opts).build();});after(async()=>await driver.quit());it('Should be able to print page to pdf',asyncfunction(){await driver.get('https://www.selenium.dev/selenium/web/alerts.html');let base64 =await driver.printPage({pageRanges:["1-2"]});// page can be saved as a PDF as below// await fs.writeFileSync('./test.pdf', base64, 'base64');
base64Code = base64.slice(startIndex, endIndex)
assert.strictEqual(base64Code, pdfMagicNumber)});it('Should be able to get text using executeScript',asyncfunction(){await driver.get('https://www.selenium.dev/selenium/web/javascriptPage.html');// Stores the header elementlet header =await driver.findElement(By.css('h1'));// Executing JavaScript to capture innerText of header elementlet text =await driver.executeScript('return arguments[0].innerText', header);
assert.strictEqual(text,`Type Stuff`)});it('Should be able to take Element Screenshot',asyncfunction(){await driver.get('https://www.selenium.dev/selenium/web/javascriptPage.html');let header =await driver.findElement(By.css('h1'));// Captures the element screenshotlet encodedString =await header.takeScreenshot(true);// save screenshot as below// await fs.writeFileSync('./image.png', encodedString, 'base64');
base64Code = encodedString.slice(startIndex, endIndex)
assert.strictEqual(base64Code, imgMagicNumber)});it('Should be able to takeScreenshot',asyncfunction(){await driver.get('https://www.selenium.dev/selenium/web/javascriptPage.html');// Captures the screenshotlet encodedString =await driver.takeScreenshot();// save screenshot as below// await fs.writeFileSync('./image.png', encodedString, 'base64');
base64Code = encodedString.slice(startIndex, endIndex)
assert.strictEqual(base64Code, imgMagicNumber)});it('Should be able to switch to newWindow and newTab and close',asyncfunction(){await driver.get('https://www.selenium.dev/selenium/web/');const initialWindow =await driver.getAllWindowHandles();
assert.strictEqual(initialWindow.length,1)// Opens a new tab and switches to new tabawait driver.switchTo().newWindow('tab');const browserTabs =await driver.getAllWindowHandles();
assert.strictEqual(browserTabs.length,2)// Opens a new window and switches to new windowawait driver.switchTo().newWindow('window');const windows =await driver.getAllWindowHandles();
assert.strictEqual(windows.length,3)//Close the tab or windowawait driver.close();//Switch back to the old tab or windowawait driver.switchTo().window(windows[1]);const windowsAfterClose =await driver.getAllWindowHandles();
assert.strictEqual(windowsAfterClose.length,2);});it('Should be able to getWindow Size',asyncfunction(){await driver.get('https://www.selenium.dev/selenium/web/');// Access each dimension individuallyconst{ width, height }=await driver.manage().window().getRect();// Or store the dimensions and query them laterconst rect =await driver.manage().window().getRect();const windowWidth = rect.width;const windowHeight = rect.height;
assert.ok(windowWidth>0);
assert.ok(windowHeight>0);});it('Should be able to getWindow position',asyncfunction(){await driver.get('https://www.selenium.dev/selenium/web/');// Access each dimension individuallyconst{ x, y }=await driver.manage().window().getRect();// Or store the dimensions and query them laterconst rect =await driver.manage().window().getRect();const x1 = rect.x;const y1 = rect.y;
assert.ok(x1>=0);
assert.ok(y1>=0);});});
(or) store the dimensions and query them later
const rect =await driver.manage().window().getRect();const windowWidth = rect.width;const windowHeight = rect.height;
const{Builder, By}=require('selenium-webdriver');const chrome =require('selenium-webdriver/chrome');const assert =require("node:assert");let opts =newchrome.Options();
opts.addArguments('--headless');let startIndex =0let endIndex =5let pdfMagicNumber ='JVBER'let imgMagicNumber ='iVBOR'let base64Code
describe('Interactions - Windows',function(){let driver;before(asyncfunction(){
driver =awaitnewBuilder().forBrowser('chrome').setChromeOptions(opts).build();});after(async()=>await driver.quit());it('Should be able to print page to pdf',asyncfunction(){await driver.get('https://www.selenium.dev/selenium/web/alerts.html');let base64 =await driver.printPage({pageRanges:["1-2"]});// page can be saved as a PDF as below// await fs.writeFileSync('./test.pdf', base64, 'base64');
base64Code = base64.slice(startIndex, endIndex)
assert.strictEqual(base64Code, pdfMagicNumber)});it('Should be able to get text using executeScript',asyncfunction(){await driver.get('https://www.selenium.dev/selenium/web/javascriptPage.html');// Stores the header elementlet header =await driver.findElement(By.css('h1'));// Executing JavaScript to capture innerText of header elementlet text =await driver.executeScript('return arguments[0].innerText', header);
assert.strictEqual(text,`Type Stuff`)});it('Should be able to take Element Screenshot',asyncfunction(){await driver.get('https://www.selenium.dev/selenium/web/javascriptPage.html');let header =await driver.findElement(By.css('h1'));// Captures the element screenshotlet encodedString =await header.takeScreenshot(true);// save screenshot as below// await fs.writeFileSync('./image.png', encodedString, 'base64');
base64Code = encodedString.slice(startIndex, endIndex)
assert.strictEqual(base64Code, imgMagicNumber)});it('Should be able to takeScreenshot',asyncfunction(){await driver.get('https://www.selenium.dev/selenium/web/javascriptPage.html');// Captures the screenshotlet encodedString =await driver.takeScreenshot();// save screenshot as below// await fs.writeFileSync('./image.png', encodedString, 'base64');
base64Code = encodedString.slice(startIndex, endIndex)
assert.strictEqual(base64Code, imgMagicNumber)});it('Should be able to switch to newWindow and newTab and close',asyncfunction(){await driver.get('https://www.selenium.dev/selenium/web/');const initialWindow =await driver.getAllWindowHandles();
assert.strictEqual(initialWindow.length,1)// Opens a new tab and switches to new tabawait driver.switchTo().newWindow('tab');const browserTabs =await driver.getAllWindowHandles();
assert.strictEqual(browserTabs.length,2)// Opens a new window and switches to new windowawait driver.switchTo().newWindow('window');const windows =await driver.getAllWindowHandles();
assert.strictEqual(windows.length,3)//Close the tab or windowawait driver.close();//Switch back to the old tab or windowawait driver.switchTo().window(windows[1]);const windowsAfterClose =await driver.getAllWindowHandles();
assert.strictEqual(windowsAfterClose.length,2);});it('Should be able to getWindow Size',asyncfunction(){await driver.get('https://www.selenium.dev/selenium/web/');// Access each dimension individuallyconst{ width, height }=await driver.manage().window().getRect();// Or store the dimensions and query them laterconst rect =await driver.manage().window().getRect();const windowWidth = rect.width;const windowHeight = rect.height;
assert.ok(windowWidth>0);
assert.ok(windowHeight>0);});it('Should be able to getWindow position',asyncfunction(){await driver.get('https://www.selenium.dev/selenium/web/');// Access each dimension individuallyconst{ x, y }=await driver.manage().window().getRect();// Or store the dimensions and query them laterconst rect =await driver.manage().window().getRect();const x1 = rect.x;const y1 = rect.y;
assert.ok(x1>=0);
assert.ok(y1>=0);});});
//Access each dimension individuallyval width = driver.manage().window().size.width
val height = driver.manage().window().size.height
//Or store the dimensions and query them laterval size = driver.manage().window().size
val width1 = size.width
val height1 = size.height
Busca as coordenadas da coordenada superior esquerda da janela do navegador.
// Access each dimension individuallyint x = driver.manage().window().getPosition().getX();int y = driver.manage().window().getPosition().getY();// Or store the dimensions and query them laterPoint position = driver.manage().window().getPosition();int x1 = position.getX();int y1 = position.getY();
# Access each dimension individually
x = driver.get_window_position().get('x')
y = driver.get_window_position().get('y')# Or store the dimensions and query them later
position = driver.get_window_position()
x1 = position.get('x')
y1 = position.get('y')
//Access each dimension individuallyint x = driver.Manage().Window.Position.X;int y = driver.Manage().Window.Position.Y;//Or store the dimensions and query them laterPoint position = driver.Manage().Window.Position;int x1 = position.X;int y1 = position.Y;
#Access each dimension individually
x = driver.manage.window.position.x
y = driver.manage.window.position.y
# Or store the dimensions and query them later
rect = driver.manage.window.rect
x1 = rect.x
y1 = rect.y
Access each dimension individually
const{ x, y }=await driver.manage().window().getRect();
const{Builder, By}=require('selenium-webdriver');const chrome =require('selenium-webdriver/chrome');const assert =require("node:assert");let opts =newchrome.Options();
opts.addArguments('--headless');let startIndex =0let endIndex =5let pdfMagicNumber ='JVBER'let imgMagicNumber ='iVBOR'let base64Code
describe('Interactions - Windows',function(){let driver;before(asyncfunction(){
driver =awaitnewBuilder().forBrowser('chrome').setChromeOptions(opts).build();});after(async()=>await driver.quit());it('Should be able to print page to pdf',asyncfunction(){await driver.get('https://www.selenium.dev/selenium/web/alerts.html');let base64 =await driver.printPage({pageRanges:["1-2"]});// page can be saved as a PDF as below// await fs.writeFileSync('./test.pdf', base64, 'base64');
base64Code = base64.slice(startIndex, endIndex)
assert.strictEqual(base64Code, pdfMagicNumber)});it('Should be able to get text using executeScript',asyncfunction(){await driver.get('https://www.selenium.dev/selenium/web/javascriptPage.html');// Stores the header elementlet header =await driver.findElement(By.css('h1'));// Executing JavaScript to capture innerText of header elementlet text =await driver.executeScript('return arguments[0].innerText', header);
assert.strictEqual(text,`Type Stuff`)});it('Should be able to take Element Screenshot',asyncfunction(){await driver.get('https://www.selenium.dev/selenium/web/javascriptPage.html');let header =await driver.findElement(By.css('h1'));// Captures the element screenshotlet encodedString =await header.takeScreenshot(true);// save screenshot as below// await fs.writeFileSync('./image.png', encodedString, 'base64');
base64Code = encodedString.slice(startIndex, endIndex)
assert.strictEqual(base64Code, imgMagicNumber)});it('Should be able to takeScreenshot',asyncfunction(){await driver.get('https://www.selenium.dev/selenium/web/javascriptPage.html');// Captures the screenshotlet encodedString =await driver.takeScreenshot();// save screenshot as below// await fs.writeFileSync('./image.png', encodedString, 'base64');
base64Code = encodedString.slice(startIndex, endIndex)
assert.strictEqual(base64Code, imgMagicNumber)});it('Should be able to switch to newWindow and newTab and close',asyncfunction(){await driver.get('https://www.selenium.dev/selenium/web/');const initialWindow =await driver.getAllWindowHandles();
assert.strictEqual(initialWindow.length,1)// Opens a new tab and switches to new tabawait driver.switchTo().newWindow('tab');const browserTabs =await driver.getAllWindowHandles();
assert.strictEqual(browserTabs.length,2)// Opens a new window and switches to new windowawait driver.switchTo().newWindow('window');const windows =await driver.getAllWindowHandles();
assert.strictEqual(windows.length,3)//Close the tab or windowawait driver.close();//Switch back to the old tab or windowawait driver.switchTo().window(windows[1]);const windowsAfterClose =await driver.getAllWindowHandles();
assert.strictEqual(windowsAfterClose.length,2);});it('Should be able to getWindow Size',asyncfunction(){await driver.get('https://www.selenium.dev/selenium/web/');// Access each dimension individuallyconst{ width, height }=await driver.manage().window().getRect();// Or store the dimensions and query them laterconst rect =await driver.manage().window().getRect();const windowWidth = rect.width;const windowHeight = rect.height;
assert.ok(windowWidth>0);
assert.ok(windowHeight>0);});it('Should be able to getWindow position',asyncfunction(){await driver.get('https://www.selenium.dev/selenium/web/');// Access each dimension individuallyconst{ x, y }=await driver.manage().window().getRect();// Or store the dimensions and query them laterconst rect =await driver.manage().window().getRect();const x1 = rect.x;const y1 = rect.y;
assert.ok(x1>=0);
assert.ok(y1>=0);});});
(or) store the dimensions and query them later
const rect =await driver.manage().window().getRect();const x1 = rect.x;const y1 = rect.y;
const{Builder, By}=require('selenium-webdriver');const chrome =require('selenium-webdriver/chrome');const assert =require("node:assert");let opts =newchrome.Options();
opts.addArguments('--headless');let startIndex =0let endIndex =5let pdfMagicNumber ='JVBER'let imgMagicNumber ='iVBOR'let base64Code
describe('Interactions - Windows',function(){let driver;before(asyncfunction(){
driver =awaitnewBuilder().forBrowser('chrome').setChromeOptions(opts).build();});after(async()=>await driver.quit());it('Should be able to print page to pdf',asyncfunction(){await driver.get('https://www.selenium.dev/selenium/web/alerts.html');let base64 =await driver.printPage({pageRanges:["1-2"]});// page can be saved as a PDF as below// await fs.writeFileSync('./test.pdf', base64, 'base64');
base64Code = base64.slice(startIndex, endIndex)
assert.strictEqual(base64Code, pdfMagicNumber)});it('Should be able to get text using executeScript',asyncfunction(){await driver.get('https://www.selenium.dev/selenium/web/javascriptPage.html');// Stores the header elementlet header =await driver.findElement(By.css('h1'));// Executing JavaScript to capture innerText of header elementlet text =await driver.executeScript('return arguments[0].innerText', header);
assert.strictEqual(text,`Type Stuff`)});it('Should be able to take Element Screenshot',asyncfunction(){await driver.get('https://www.selenium.dev/selenium/web/javascriptPage.html');let header =await driver.findElement(By.css('h1'));// Captures the element screenshotlet encodedString =await header.takeScreenshot(true);// save screenshot as below// await fs.writeFileSync('./image.png', encodedString, 'base64');
base64Code = encodedString.slice(startIndex, endIndex)
assert.strictEqual(base64Code, imgMagicNumber)});it('Should be able to takeScreenshot',asyncfunction(){await driver.get('https://www.selenium.dev/selenium/web/javascriptPage.html');// Captures the screenshotlet encodedString =await driver.takeScreenshot();// save screenshot as below// await fs.writeFileSync('./image.png', encodedString, 'base64');
base64Code = encodedString.slice(startIndex, endIndex)
assert.strictEqual(base64Code, imgMagicNumber)});it('Should be able to switch to newWindow and newTab and close',asyncfunction(){await driver.get('https://www.selenium.dev/selenium/web/');const initialWindow =await driver.getAllWindowHandles();
assert.strictEqual(initialWindow.length,1)// Opens a new tab and switches to new tabawait driver.switchTo().newWindow('tab');const browserTabs =await driver.getAllWindowHandles();
assert.strictEqual(browserTabs.length,2)// Opens a new window and switches to new windowawait driver.switchTo().newWindow('window');const windows =await driver.getAllWindowHandles();
assert.strictEqual(windows.length,3)//Close the tab or windowawait driver.close();//Switch back to the old tab or windowawait driver.switchTo().window(windows[1]);const windowsAfterClose =await driver.getAllWindowHandles();
assert.strictEqual(windowsAfterClose.length,2);});it('Should be able to getWindow Size',asyncfunction(){await driver.get('https://www.selenium.dev/selenium/web/');// Access each dimension individuallyconst{ width, height }=await driver.manage().window().getRect();// Or store the dimensions and query them laterconst rect =await driver.manage().window().getRect();const windowWidth = rect.width;const windowHeight = rect.height;
assert.ok(windowWidth>0);
assert.ok(windowHeight>0);});it('Should be able to getWindow position',asyncfunction(){await driver.get('https://www.selenium.dev/selenium/web/');// Access each dimension individuallyconst{ x, y }=await driver.manage().window().getRect();// Or store the dimensions and query them laterconst rect =await driver.manage().window().getRect();const x1 = rect.x;const y1 = rect.y;
assert.ok(x1>=0);
assert.ok(y1>=0);});});
// Access each dimension individuallyval x = driver.manage().window().position.x
val y = driver.manage().window().position.y
// Or store the dimensions and query them laterval position = driver.manage().window().position
val x1 = position.x
val y1 = position.y
Definir posição da janela
Move a janela para a posição escolhida.
// Move the window to the top left of the primary monitor
driver.manage().window().setPosition(newPoint(0,0));
# Move the window to the top left of the primary monitor
driver.set_window_position(0,0)
// Move the window to the top left of the primary monitor
driver.Manage().Window.Position =newPoint(0,0);
driver.manage.window.move_to(0,0)
// Move the window to the top left of the primary monitorawait driver.manage().window().setRect({x:0,y:0});
// Move the window to the top left of the primary monitor
driver.manage().window().position =Point(0,0)
Maximizar janela
Aumenta a janela. Para a maioria dos sistemas operacionais, a janela irá preencher
a tela, sem bloquear os próprios menus do sistema operacional e
barras de ferramentas.
driver.manage().window().maximize();
driver.maximize_window()
driver.Manage().Window.Maximize();
driver.manage.window.maximize
await driver.manage().window().maximize();
driver.manage().window().maximize()
Minimizar janela
Minimiza a janela do contexto de navegação atual.
O comportamento exato deste comando é específico para
gerenciadores de janela individuais.
Minimizar Janela normalmente oculta a janela na bandeja do sistema.
Nota: este recurso funciona com Selenium 4 e versões posteriores.
driver.manage().window().minimize();
driver.minimize_window()
driver.Manage().Window.Minimize();
driver.manage.window.minimize
await driver.manage().window().minimize();
driver.manage().window().minimize()
Janela em tamanho cheio
Preenche a tela inteira, semelhante a pressionar F11 na maioria dos navegadores.
driver.manage().window().fullscreen();
driver.fullscreen_window()
driver.Manage().Window.FullScreen();
driver.manage.window.full_screen
await driver.manage().window().fullscreen();
driver.manage().window().fullscreen()
TakeScreenshot
Usado para capturar a tela do contexto de navegação atual.
O endpoint WebDriver screenshot
retorna a captura de tela codificada no formato Base64.
from selenium import webdriver
driver = webdriver.Chrome()# Navigate to url
driver.get("http://www.example.com")# Returns and base64 encoded string into image
driver.save_screenshot('./image.png')
driver.quit()
usingOpenQA.Selenium;usingOpenQA.Selenium.Chrome;usingOpenQA.Selenium.Support.UI;var driver =newChromeDriver();
driver.Navigate().GoToUrl("http://www.example.com");Screenshot screenshot =(driver asITakesScreenshot).GetScreenshot();
screenshot.SaveAsFile("screenshot.png", ScreenshotImageFormat.Png);// Format values are Bmp, Gif, Jpeg, Png, Tiff
require'selenium-webdriver'
driver =Selenium::WebDriver.for:chromebegin
driver.get 'https://example.com/'# Takes and Stores the screenshot in specified path
driver.save_screenshot('./image.png')end
// Captures the screenshotlet encodedString =await driver.takeScreenshot();// save screenshot as below// await fs.writeFileSync('./image.png', encodedString, 'base64');
const{Builder, By}=require('selenium-webdriver');const chrome =require('selenium-webdriver/chrome');const assert =require("node:assert");let opts =newchrome.Options();
opts.addArguments('--headless');let startIndex =0let endIndex =5let pdfMagicNumber ='JVBER'let imgMagicNumber ='iVBOR'let base64Code
describe('Interactions - Windows',function(){let driver;before(asyncfunction(){
driver =awaitnewBuilder().forBrowser('chrome').setChromeOptions(opts).build();});after(async()=>await driver.quit());it('Should be able to print page to pdf',asyncfunction(){await driver.get('https://www.selenium.dev/selenium/web/alerts.html');let base64 =await driver.printPage({pageRanges:["1-2"]});// page can be saved as a PDF as below// await fs.writeFileSync('./test.pdf', base64, 'base64');
base64Code = base64.slice(startIndex, endIndex)
assert.strictEqual(base64Code, pdfMagicNumber)});it('Should be able to get text using executeScript',asyncfunction(){await driver.get('https://www.selenium.dev/selenium/web/javascriptPage.html');// Stores the header elementlet header =await driver.findElement(By.css('h1'));// Executing JavaScript to capture innerText of header elementlet text =await driver.executeScript('return arguments[0].innerText', header);
assert.strictEqual(text,`Type Stuff`)});it('Should be able to take Element Screenshot',asyncfunction(){await driver.get('https://www.selenium.dev/selenium/web/javascriptPage.html');let header =await driver.findElement(By.css('h1'));// Captures the element screenshotlet encodedString =await header.takeScreenshot(true);// save screenshot as below// await fs.writeFileSync('./image.png', encodedString, 'base64');
base64Code = encodedString.slice(startIndex, endIndex)
assert.strictEqual(base64Code, imgMagicNumber)});it('Should be able to takeScreenshot',asyncfunction(){await driver.get('https://www.selenium.dev/selenium/web/javascriptPage.html');// Captures the screenshotlet encodedString =await driver.takeScreenshot();// save screenshot as below// await fs.writeFileSync('./image.png', encodedString, 'base64');
base64Code = encodedString.slice(startIndex, endIndex)
assert.strictEqual(base64Code, imgMagicNumber)});it('Should be able to switch to newWindow and newTab and close',asyncfunction(){await driver.get('https://www.selenium.dev/selenium/web/');const initialWindow =await driver.getAllWindowHandles();
assert.strictEqual(initialWindow.length,1)// Opens a new tab and switches to new tabawait driver.switchTo().newWindow('tab');const browserTabs =await driver.getAllWindowHandles();
assert.strictEqual(browserTabs.length,2)// Opens a new window and switches to new windowawait driver.switchTo().newWindow('window');const windows =await driver.getAllWindowHandles();
assert.strictEqual(windows.length,3)//Close the tab or windowawait driver.close();//Switch back to the old tab or windowawait driver.switchTo().window(windows[1]);const windowsAfterClose =await driver.getAllWindowHandles();
assert.strictEqual(windowsAfterClose.length,2);});it('Should be able to getWindow Size',asyncfunction(){await driver.get('https://www.selenium.dev/selenium/web/');// Access each dimension individuallyconst{ width, height }=await driver.manage().window().getRect();// Or store the dimensions and query them laterconst rect =await driver.manage().window().getRect();const windowWidth = rect.width;const windowHeight = rect.height;
assert.ok(windowWidth>0);
assert.ok(windowHeight>0);});it('Should be able to getWindow position',asyncfunction(){await driver.get('https://www.selenium.dev/selenium/web/');// Access each dimension individuallyconst{ x, y }=await driver.manage().window().getRect();// Or store the dimensions and query them laterconst rect =await driver.manage().window().getRect();const x1 = rect.x;const y1 = rect.y;
assert.ok(x1>=0);
assert.ok(y1>=0);});});
Usado para capturar a imagem de um elemento para o contexto de navegação atual.
O endpoint WebDriver screenshot
retorna a captura de tela codificada no formato Base64.
from selenium import webdriver
from selenium.webdriver.common.by import By
driver = webdriver.Chrome()# Navigate to url
driver.get("http://www.example.com")
ele = driver.find_element(By.CSS_SELECTOR,'h1')# Returns and base64 encoded string into image
ele.screenshot('./image.png')
driver.quit()
usingOpenQA.Selenium;usingOpenQA.Selenium.Chrome;usingOpenQA.Selenium.Support.UI;// Webdrivervar driver =newChromeDriver();
driver.Navigate().GoToUrl("http://www.example.com");// Fetch element using FindElementvar webElement = driver.FindElement(By.CssSelector("h1"));// Screenshot for the elementvar elementScreenshot =(webElement asITakesScreenshot).GetScreenshot();
elementScreenshot.SaveAsFile("screenshot_of_element.png");
# Works with Selenium4-alpha7 Ruby bindings and aboverequire'selenium-webdriver'
driver =Selenium::WebDriver.for:chromebegin
driver.get 'https://example.com/'
ele = driver.find_element(:css,'h1')# Takes and Stores the element screenshot in specified path
ele.save_screenshot('./image.jpg')end
let header =await driver.findElement(By.css('h1'));// Captures the element screenshotlet encodedString =await header.takeScreenshot(true);// save screenshot as below// await fs.writeFileSync('./image.png', encodedString, 'base64');
const{Builder, By}=require('selenium-webdriver');const chrome =require('selenium-webdriver/chrome');const assert =require("node:assert");let opts =newchrome.Options();
opts.addArguments('--headless');let startIndex =0let endIndex =5let pdfMagicNumber ='JVBER'let imgMagicNumber ='iVBOR'let base64Code
describe('Interactions - Windows',function(){let driver;before(asyncfunction(){
driver =awaitnewBuilder().forBrowser('chrome').setChromeOptions(opts).build();});after(async()=>await driver.quit());it('Should be able to print page to pdf',asyncfunction(){await driver.get('https://www.selenium.dev/selenium/web/alerts.html');let base64 =await driver.printPage({pageRanges:["1-2"]});// page can be saved as a PDF as below// await fs.writeFileSync('./test.pdf', base64, 'base64');
base64Code = base64.slice(startIndex, endIndex)
assert.strictEqual(base64Code, pdfMagicNumber)});it('Should be able to get text using executeScript',asyncfunction(){await driver.get('https://www.selenium.dev/selenium/web/javascriptPage.html');// Stores the header elementlet header =await driver.findElement(By.css('h1'));// Executing JavaScript to capture innerText of header elementlet text =await driver.executeScript('return arguments[0].innerText', header);
assert.strictEqual(text,`Type Stuff`)});it('Should be able to take Element Screenshot',asyncfunction(){await driver.get('https://www.selenium.dev/selenium/web/javascriptPage.html');let header =await driver.findElement(By.css('h1'));// Captures the element screenshotlet encodedString =await header.takeScreenshot(true);// save screenshot as below// await fs.writeFileSync('./image.png', encodedString, 'base64');
base64Code = encodedString.slice(startIndex, endIndex)
assert.strictEqual(base64Code, imgMagicNumber)});it('Should be able to takeScreenshot',asyncfunction(){await driver.get('https://www.selenium.dev/selenium/web/javascriptPage.html');// Captures the screenshotlet encodedString =await driver.takeScreenshot();// save screenshot as below// await fs.writeFileSync('./image.png', encodedString, 'base64');
base64Code = encodedString.slice(startIndex, endIndex)
assert.strictEqual(base64Code, imgMagicNumber)});it('Should be able to switch to newWindow and newTab and close',asyncfunction(){await driver.get('https://www.selenium.dev/selenium/web/');const initialWindow =await driver.getAllWindowHandles();
assert.strictEqual(initialWindow.length,1)// Opens a new tab and switches to new tabawait driver.switchTo().newWindow('tab');const browserTabs =await driver.getAllWindowHandles();
assert.strictEqual(browserTabs.length,2)// Opens a new window and switches to new windowawait driver.switchTo().newWindow('window');const windows =await driver.getAllWindowHandles();
assert.strictEqual(windows.length,3)//Close the tab or windowawait driver.close();//Switch back to the old tab or windowawait driver.switchTo().window(windows[1]);const windowsAfterClose =await driver.getAllWindowHandles();
assert.strictEqual(windowsAfterClose.length,2);});it('Should be able to getWindow Size',asyncfunction(){await driver.get('https://www.selenium.dev/selenium/web/');// Access each dimension individuallyconst{ width, height }=await driver.manage().window().getRect();// Or store the dimensions and query them laterconst rect =await driver.manage().window().getRect();const windowWidth = rect.width;const windowHeight = rect.height;
assert.ok(windowWidth>0);
assert.ok(windowHeight>0);});it('Should be able to getWindow position',asyncfunction(){await driver.get('https://www.selenium.dev/selenium/web/');// Access each dimension individuallyconst{ x, y }=await driver.manage().window().getRect();// Or store the dimensions and query them laterconst rect =await driver.manage().window().getRect();const x1 = rect.x;const y1 = rect.y;
assert.ok(x1>=0);
assert.ok(y1>=0);});});
Executa o snippet de código JavaScript no
contexto atual de um frame ou janela selecionada.
//Creating the JavascriptExecutor interface object by Type castingJavascriptExecutor js =(JavascriptExecutor)driver;//Button ElementWebElement button =driver.findElement(By.name("btnLogin"));//Executing JavaScript to click on element
js.executeScript("arguments[0].click();", button);//Get return value from scriptString text =(String) js.executeScript("return arguments[0].innerText", button);//Executing JavaScript directly
js.executeScript("console.log('hello world')");
# Stores the header element
header = driver.find_element(By.CSS_SELECTOR,"h1")# Executing JavaScript to capture innerText of header element
driver.execute_script('return arguments[0].innerText', header)
//creating Chromedriver instanceIWebDriver driver =newChromeDriver();//Creating the JavascriptExecutor interface object by Type castingIJavaScriptExecutor js =(IJavaScriptExecutor) driver;//Button ElementIWebElement button = driver.FindElement(By.Name("btnLogin"));//Executing JavaScript to click on element
js.ExecuteScript("arguments[0].click();", button);//Get return value from scriptString text =(String)js.ExecuteScript("return arguments[0].innerText", button);//Executing JavaScript directly
js.ExecuteScript("console.log('hello world')");
# Stores the header element
header = driver.find_element(css:'h1')# Get return value from script
result = driver.execute_script("return arguments[0].innerText", header)# Executing JavaScript directly
driver.execute_script("alert('hello world')")
// Stores the header elementlet header =await driver.findElement(By.css('h1'));// Executing JavaScript to capture innerText of header elementlet text =await driver.executeScript('return arguments[0].innerText', header);
const{Builder, By}=require('selenium-webdriver');const chrome =require('selenium-webdriver/chrome');const assert =require("node:assert");let opts =newchrome.Options();
opts.addArguments('--headless');let startIndex =0let endIndex =5let pdfMagicNumber ='JVBER'let imgMagicNumber ='iVBOR'let base64Code
describe('Interactions - Windows',function(){let driver;before(asyncfunction(){
driver =awaitnewBuilder().forBrowser('chrome').setChromeOptions(opts).build();});after(async()=>await driver.quit());it('Should be able to print page to pdf',asyncfunction(){await driver.get('https://www.selenium.dev/selenium/web/alerts.html');let base64 =await driver.printPage({pageRanges:["1-2"]});// page can be saved as a PDF as below// await fs.writeFileSync('./test.pdf', base64, 'base64');
base64Code = base64.slice(startIndex, endIndex)
assert.strictEqual(base64Code, pdfMagicNumber)});it('Should be able to get text using executeScript',asyncfunction(){await driver.get('https://www.selenium.dev/selenium/web/javascriptPage.html');// Stores the header elementlet header =await driver.findElement(By.css('h1'));// Executing JavaScript to capture innerText of header elementlet text =await driver.executeScript('return arguments[0].innerText', header);
assert.strictEqual(text,`Type Stuff`)});it('Should be able to take Element Screenshot',asyncfunction(){await driver.get('https://www.selenium.dev/selenium/web/javascriptPage.html');let header =await driver.findElement(By.css('h1'));// Captures the element screenshotlet encodedString =await header.takeScreenshot(true);// save screenshot as below// await fs.writeFileSync('./image.png', encodedString, 'base64');
base64Code = encodedString.slice(startIndex, endIndex)
assert.strictEqual(base64Code, imgMagicNumber)});it('Should be able to takeScreenshot',asyncfunction(){await driver.get('https://www.selenium.dev/selenium/web/javascriptPage.html');// Captures the screenshotlet encodedString =await driver.takeScreenshot();// save screenshot as below// await fs.writeFileSync('./image.png', encodedString, 'base64');
base64Code = encodedString.slice(startIndex, endIndex)
assert.strictEqual(base64Code, imgMagicNumber)});it('Should be able to switch to newWindow and newTab and close',asyncfunction(){await driver.get('https://www.selenium.dev/selenium/web/');const initialWindow =await driver.getAllWindowHandles();
assert.strictEqual(initialWindow.length,1)// Opens a new tab and switches to new tabawait driver.switchTo().newWindow('tab');const browserTabs =await driver.getAllWindowHandles();
assert.strictEqual(browserTabs.length,2)// Opens a new window and switches to new windowawait driver.switchTo().newWindow('window');const windows =await driver.getAllWindowHandles();
assert.strictEqual(windows.length,3)//Close the tab or windowawait driver.close();//Switch back to the old tab or windowawait driver.switchTo().window(windows[1]);const windowsAfterClose =await driver.getAllWindowHandles();
assert.strictEqual(windowsAfterClose.length,2);});it('Should be able to getWindow Size',asyncfunction(){await driver.get('https://www.selenium.dev/selenium/web/');// Access each dimension individuallyconst{ width, height }=await driver.manage().window().getRect();// Or store the dimensions and query them laterconst rect =await driver.manage().window().getRect();const windowWidth = rect.width;const windowHeight = rect.height;
assert.ok(windowWidth>0);
assert.ok(windowHeight>0);});it('Should be able to getWindow position',asyncfunction(){await driver.get('https://www.selenium.dev/selenium/web/');// Access each dimension individuallyconst{ x, y }=await driver.manage().window().getRect();// Or store the dimensions and query them laterconst rect =await driver.manage().window().getRect();const x1 = rect.x;const y1 = rect.y;
assert.ok(x1>=0);
assert.ok(y1>=0);});});
// Stores the header elementval header = driver.findElement(By.cssSelector("h1"))// Get return value from scriptval result = driver.executeScript("return arguments[0].innerText", header)// Executing JavaScript directly
driver.executeScript("alert('hello world')")
Imprimir Página
Imprime a página atual dentro do navegador
Nota: isto requer que navegadores Chromium estejam no modo sem cabeçalho
await driver.get('https://www.selenium.dev/selenium/web/alerts.html');let base64 =await driver.printPage({pageRanges:["1-2"]});// page can be saved as a PDF as below// await fs.writeFileSync('./test.pdf', base64, 'base64');
const{Builder, By}=require('selenium-webdriver');const chrome =require('selenium-webdriver/chrome');const assert =require("node:assert");let opts =newchrome.Options();
opts.addArguments('--headless');let startIndex =0let endIndex =5let pdfMagicNumber ='JVBER'let imgMagicNumber ='iVBOR'let base64Code
describe('Interactions - Windows',function(){let driver;before(asyncfunction(){
driver =awaitnewBuilder().forBrowser('chrome').setChromeOptions(opts).build();});after(async()=>await driver.quit());it('Should be able to print page to pdf',asyncfunction(){await driver.get('https://www.selenium.dev/selenium/web/alerts.html');let base64 =await driver.printPage({pageRanges:["1-2"]});// page can be saved as a PDF as below// await fs.writeFileSync('./test.pdf', base64, 'base64');
base64Code = base64.slice(startIndex, endIndex)
assert.strictEqual(base64Code, pdfMagicNumber)});it('Should be able to get text using executeScript',asyncfunction(){await driver.get('https://www.selenium.dev/selenium/web/javascriptPage.html');// Stores the header elementlet header =await driver.findElement(By.css('h1'));// Executing JavaScript to capture innerText of header elementlet text =await driver.executeScript('return arguments[0].innerText', header);
assert.strictEqual(text,`Type Stuff`)});it('Should be able to take Element Screenshot',asyncfunction(){await driver.get('https://www.selenium.dev/selenium/web/javascriptPage.html');let header =await driver.findElement(By.css('h1'));// Captures the element screenshotlet encodedString =await header.takeScreenshot(true);// save screenshot as below// await fs.writeFileSync('./image.png', encodedString, 'base64');
base64Code = encodedString.slice(startIndex, endIndex)
assert.strictEqual(base64Code, imgMagicNumber)});it('Should be able to takeScreenshot',asyncfunction(){await driver.get('https://www.selenium.dev/selenium/web/javascriptPage.html');// Captures the screenshotlet encodedString =await driver.takeScreenshot();// save screenshot as below// await fs.writeFileSync('./image.png', encodedString, 'base64');
base64Code = encodedString.slice(startIndex, endIndex)
assert.strictEqual(base64Code, imgMagicNumber)});it('Should be able to switch to newWindow and newTab and close',asyncfunction(){await driver.get('https://www.selenium.dev/selenium/web/');const initialWindow =await driver.getAllWindowHandles();
assert.strictEqual(initialWindow.length,1)// Opens a new tab and switches to new tabawait driver.switchTo().newWindow('tab');const browserTabs =await driver.getAllWindowHandles();
assert.strictEqual(browserTabs.length,2)// Opens a new window and switches to new windowawait driver.switchTo().newWindow('window');const windows =await driver.getAllWindowHandles();
assert.strictEqual(windows.length,3)//Close the tab or windowawait driver.close();//Switch back to the old tab or windowawait driver.switchTo().window(windows[1]);const windowsAfterClose =await driver.getAllWindowHandles();
assert.strictEqual(windowsAfterClose.length,2);});it('Should be able to getWindow Size',asyncfunction(){await driver.get('https://www.selenium.dev/selenium/web/');// Access each dimension individuallyconst{ width, height }=await driver.manage().window().getRect();// Or store the dimensions and query them laterconst rect =await driver.manage().window().getRect();const windowWidth = rect.width;const windowHeight = rect.height;
assert.ok(windowWidth>0);
assert.ok(windowHeight>0);});it('Should be able to getWindow position',asyncfunction(){await driver.get('https://www.selenium.dev/selenium/web/');// Access each dimension individuallyconst{ x, y }=await driver.manage().window().getRect();// Or store the dimensions and query them laterconst rect =await driver.manage().window().getRect();const x1 = rect.x;const y1 = rect.y;
assert.ok(x1>=0);
assert.ok(y1>=0);});});
driver.get("https://www.selenium.dev")val printer = driver as PrintsPage
val printOptions =PrintOptions()
printOptions.setPageRanges("1-2")val pdf: Pdf = printer.print(printOptions)val content = pdf.content
7 - Virtual Authenticator
Uma representação do modelo Web Authenticator.
Aplicações web podem habilitar um mecanismo de autenticação baseado em chaves públicas conhecido como Web Authentication para autenticar usuários sem usar uma senha.
Web Authentication define APIs que permitem ao usuário criar uma credencial e registra-la com um autenticador.
Um autenticador pode ser um dispositivo ou um software que guarde as chaves públicas do usuário e as acesse caso seja pedido.
Como o nome sugere, Virtual Authenticator emula esses autenticadores para testes.
Virtual Authenticator Options
Um Autenticador Virtual tem uma série de propriedades.
Essas propriedades são mapeadas como VirtualAuthenticatorOptions nos bindings do Selenium.
import pytest
from base64 import urlsafe_b64decode, urlsafe_b64encode
from selenium.common.exceptions import InvalidArgumentException
from selenium.webdriver.chrome.webdriver import WebDriver
from selenium.webdriver.common.virtual_authenticator import(
Credential,
VirtualAuthenticatorOptions,)
BASE64__ENCODED_PK ='''
MIIEvAIBADANBgkqhkiG9w0BAQEFAASCBKYwggSiAgEAAoIBAQDbBOu5Lhs4vpowbCnmCyLUpIE7JM9sm9QXzye2G+jr+Kr
MsinWohEce47BFPJlTaDzHSvOW2eeunBO89ZcvvVc8RLz4qyQ8rO98xS1jtgqi1NcBPETDrtzthODu/gd0sjB2Tk3TLuBGV
oPXt54a+Oo4JbBJ6h3s0+5eAfGplCbSNq6hN3Jh9YOTw5ZA6GCEy5l8zBaOgjXytd2v2OdSVoEDNiNQRkjJd2rmS2oi9AyQ
FR3B7BrPSiDlCcITZFOWgLF5C31Wp/PSHwQhlnh7/6YhnE2y9tzsUvzx0wJXrBADW13+oMxrneDK3WGbxTNYgIi1PvSqXlq
GjHtCK+R2QkXAgMBAAECggEAVc6bu7VAnP6v0gDOeX4razv4FX/adCao9ZsHZ+WPX8PQxtmWYqykH5CY4TSfsuizAgyPuQ0
+j4Vjssr9VODLqFoanspT6YXsvaKanncUYbasNgUJnfnLnw3an2XpU2XdmXTNYckCPRX9nsAAURWT3/n9ljc/XYY22ecYxM
8sDWnHu2uKZ1B7M3X60bQYL5T/lVXkKdD6xgSNLeP4AkRx0H4egaop68hoW8FIwmDPVWYVAvo8etzWCtibRXz5FcNld9MgD
/Ai7ycKy4Q1KhX5GBFI79MVVaHkSQfxPHpr7/XcmpQOEAr+BMPon4s4vnKqAGdGB3j/E3d/+4F2swykoQKBgQD8hCsp6FIQ
5umJlk9/j/nGsMl85LgLaNVYpWlPRKPc54YNumtvj5vx1BG+zMbT7qIE3nmUPTCHP7qb5ERZG4CdMCS6S64/qzZEqijLCqe
pwj6j4fV5SyPWEcpxf6ehNdmcfgzVB3Wolfwh1ydhx/96L1jHJcTKchdJJzlfTvq8wwKBgQDeCnKws1t5GapfE1rmC/h4ol
L2qZTth9oQmbrXYohVnoqNFslDa43ePZwL9Jmd9kYb0axOTNMmyrP0NTj41uCfgDS0cJnNTc63ojKjegxHIyYDKRZNVUR/d
xAYB/vPfBYZUS7M89pO6LLsHhzS3qpu3/hppo/Uc/AM/r8PSflNHQKBgDnWgBh6OQncChPUlOLv9FMZPR1ZOfqLCYrjYEqi
uzGm6iKM13zXFO4AGAxu1P/IAd5BovFcTpg79Z8tWqZaUUwvscnl+cRlj+mMXAmdqCeO8VASOmqM1ml667axeZDIR867ZG8
K5V029Wg+4qtX5uFypNAAi6GfHkxIKrD04yOHAoGACdh4wXESi0oiDdkz3KOHPwIjn6BhZC7z8mx+pnJODU3cYukxv3WTct
lUhAsyjJiQ/0bK1yX87ulqFVgO0Knmh+wNajrb9wiONAJTMICG7tiWJOm7fW5cfTJwWkBwYADmkfTRmHDvqzQSSvoC2S7aa
9QulbC3C/qgGFNrcWgcT9kCgYAZTa1P9bFCDU7hJc2mHwJwAW7/FQKEJg8SL33KINpLwcR8fqaYOdAHWWz636osVEqosRrH
zJOGpf9x2RSWzQJ+dq8+6fACgfFZOVpN644+sAHfNPAI/gnNKU5OfUv+eav8fBnzlf1A3y3GIkyMyzFN3DE7e0n/lyqxE4H
BYGpI8g==
'''@pytest.fixture(scope="module", autouse=True)defdriver():yield WebDriver()deftest_virtual_authenticator_options():
options = VirtualAuthenticatorOptions()
options.is_user_verified =True
options.has_user_verification =True
options.is_user_consenting =True
options.transport = VirtualAuthenticatorOptions.Transport.USB
options.protocol = VirtualAuthenticatorOptions.Protocol.U2F
options.has_resident_key =Falseassertlen(options.to_dict())==6deftest_add_authenticator(driver):# Create virtual authenticator options
options = VirtualAuthenticatorOptions()
options.protocol = VirtualAuthenticatorOptions.Protocol.U2F
options.has_resident_key =False# Register a virtual authenticator
driver.add_virtual_authenticator(options)# Get list of credentials
credential_list = driver.get_credentials()assertlen(credential_list)==0deftest_remove_authenticator(driver):# Create default virtual authenticator option
options = VirtualAuthenticatorOptions()# Register a virtual authenticator
driver.add_virtual_authenticator(options)# Remove virtual authenticator
driver.remove_virtual_authenticator()assert driver.virtual_authenticator_id isNonedeftest_create_and_add_resident_key(driver):# Create virtual authenticator options
options = VirtualAuthenticatorOptions()
options.protocol = VirtualAuthenticatorOptions.Protocol.CTAP2
options.has_resident_key =True
options.has_user_verification =True
options.is_user_verified =True# Register a virtual authenticator
driver.add_virtual_authenticator(options)# parameters for Resident Credential
credential_id =bytearray({1,2,3,4})
rp_id ="localhost"
user_handle =bytearray({1})
privatekey = urlsafe_b64decode(BASE64__ENCODED_PK)
sign_count =0# create a resident credential using above parameters
resident_credential = Credential.create_resident_credential(credential_id, rp_id, user_handle, privatekey, sign_count)# add the credential created to virtual authenticator
driver.add_credential(resident_credential)# get list of all the registered credentials
credential_list = driver.get_credentials()assertlen(credential_list)==1deftest_add_resident_credential_not_supported_when_authenticator_uses_u2f_protocol(driver):# Create virtual authenticator options
options = VirtualAuthenticatorOptions()
options.protocol = VirtualAuthenticatorOptions.Protocol.U2F
options.has_resident_key =False# Register a virtual authenticator
driver.add_virtual_authenticator(options)# parameters for Resident Credential
credential_id =bytearray({1,2,3,4})
rp_id ="localhost"
user_handle =bytearray({1})
privatekey = urlsafe_b64decode(BASE64__ENCODED_PK)
sign_count =0# create a resident credential using above parameters
credential = Credential.create_resident_credential(credential_id, rp_id, user_handle, privatekey, sign_count)# Expect InvalidArgumentException with pytest.raises(InvalidArgumentException):
driver.add_credential(credential)deftest_create_and_add_non_resident_key(driver):# Create virtual authenticator options
options = VirtualAuthenticatorOptions()
options.protocol = VirtualAuthenticatorOptions.Protocol.U2F
options.has_resident_key =False# Register a virtual authenticator
driver.add_virtual_authenticator(options)# parameters for Non Resident Credential
credential_id =bytearray({1,2,3,4})
rp_id ="localhost"
privatekey = urlsafe_b64decode(BASE64__ENCODED_PK)
sign_count =0# create a non resident credential using above parameters
credential = Credential.create_non_resident_credential(credential_id, rp_id, privatekey, sign_count)# add the credential created to virtual authenticator
driver.add_credential(credential)# get list of all the registered credentials
credential_list = driver.get_credentials()assertlen(credential_list)==1deftest_get_credential(driver):# Create virtual authenticator options
options = VirtualAuthenticatorOptions()
options.protocol = VirtualAuthenticatorOptions.Protocol.CTAP2
options.has_resident_key =True
options.has_user_verfied =True
options.is_user_verified =True# Register a virtual authenticator
driver.add_virtual_authenticator(options)# parameters for Resident Credential
credential_id =bytearray({1,2,3,4})
rp_id ="localhost"
user_handle =bytearray({1})
privatekey = urlsafe_b64decode(BASE64__ENCODED_PK)
sign_count =0# create a resident credential using above parameters
credential = Credential.create_resident_credential(credential_id, rp_id, user_handle, privatekey, sign_count)# add the credential created to virtual authenticator
driver.add_credential(credential)# get list of all the registered credentials
credential_list = driver.get_credentials()assertlen(credential_list)==1assert credential_list[0].id== urlsafe_b64encode(credential_id).decode()deftest_remove_credential(driver):# Create default virtual authenticator options
options = VirtualAuthenticatorOptions()# Register a virtual authenticator
driver.add_virtual_authenticator(options)# parameters for Non Resident Credential
credential_id =bytearray({1,2,3,4})
rp_id ="localhost"
privatekey = urlsafe_b64decode(BASE64__ENCODED_PK)
sign_count =0# create a non resident credential using above parameters
credential = Credential.create_non_resident_credential(credential_id, rp_id, privatekey, sign_count)# add the credential created to virtual authenticator
driver.add_credential(credential)# remove the credential created from virtual authenticator
driver.remove_credential(credential.id)# credential can also be removed using Byte Array# driver.remove_credential(credential_id) assertlen(driver.get_credentials())==0deftest_remove_all_credentials(driver):# Create default virtual authenticator options
options = VirtualAuthenticatorOptions()
options.has_resident_key =True# Register a virtual authenticator
driver.add_virtual_authenticator(options)# parameters for Resident Credential
credential_id =bytearray({1,2,3,4})
rp_id ="localhost"
user_handle =bytearray({1})
privatekey = urlsafe_b64decode(BASE64__ENCODED_PK)
sign_count =0# create a resident credential using above parameters
resident_credential = Credential.create_resident_credential(credential_id, rp_id, user_handle, privatekey, sign_count)# add the credential created to virtual authenticator
driver.add_credential(resident_credential)# remove all credentials in virtual authenticator
driver.remove_all_credentials()assertlen(driver.get_credentials())==0deftest_set_user_verified():# Create virtual authenticator options
options = VirtualAuthenticatorOptions()
options.is_user_verified =Trueassert options.to_dict().get("isUserVerified")isTrue
let nonResidentCredential =newCredential().createNonResidentCredential(newUint8Array([1,2,3,4]),'localhost',
Buffer.from(base64EncodedPK,'base64').toString('binary'),0);