from selenium import webdriver
from selenium.webdriver.chrome.service import Service
defgeoLocationTest():
driver = webdriver.Chrome()
Map_coordinates =dict({"latitude":41.8781,"longitude":-87.6298,"accuracy":100})
driver.execute_cdp_cmd("Emulation.setGeolocationOverride", Map_coordinates)
driver.get("<your site url>")
usingSystem.Threading.Tasks;usingOpenQA.Selenium.Chrome;usingOpenQA.Selenium.DevTools;// Replace the version to match the Chrome versionusingOpenQA.Selenium.DevTools.V87.Emulation;namespacedotnet_test{classProgram{publicstaticvoidMain(string[] args){GeoLocation().GetAwaiter().GetResult();}publicstaticasyncTaskGeoLocation(){ChromeDriver driver =newChromeDriver();DevToolsSession devToolsSession = driver.CreateDevToolsSession();var geoLocationOverrideCommandSettings =newSetGeolocationOverrideCommandSettings();
geoLocationOverrideCommandSettings.Latitude =51.507351;
geoLocationOverrideCommandSettings.Longitude =-0.127758;
geoLocationOverrideCommandSettings.Accuracy =1;await devToolsSession
.GetVersionSpecificDomains<OpenQA.Selenium.DevTools.V87.DevToolsSessionDomains>().Emulation
.SetGeolocationOverride(geoLocationOverrideCommandSettings);
driver.Url ="<your site url>";}}}
require'selenium-webdriver'
driver =Selenium::WebDriver.for:chromebegin# Latitude and longitude of Tokyo, Japan
coordinates ={ latitude:35.689487,
longitude:139.691706,
accuracy:100}
driver.execute_cdp('Emulation.setGeolocationOverride', coordinates)
driver.get 'https://www.google.com/search?q=selenium'ensure
driver.quit
end
const{ By, Key, Browser}=require('selenium-webdriver');const{ suite }=require('selenium-webdriver/testing');const assert =require("assert");suite(function(env){describe('Emulate geolocation',function(){let driver;before(asyncfunction(){
driver =await env.builder().build();});after(()=> driver.quit());it('Emulate coordinates of Tokyo',asyncfunction(){const cdpConnection =await driver.createCDPConnection('page');// Latitude and longitude of Tokyo, Japanconst coordinates ={latitude:35.689487,longitude:139.691706,accuracy:100,};await cdpConnection.execute("Emulation.setGeolocationOverride",
coordinates
);await driver.get("https://kawasaki-india.com/dealer-locator/");});});},{browsers:[Browser.CHROME, Browser.FIREFOX]});
from selenium import webdriver
#Replace the version to match the Chrome versionimport selenium.webdriver.common.devtools.v93 as devtools
asyncdefgeoLocationTest():
chrome_options = webdriver.ChromeOptions()
driver = webdriver.Remote(
command_executor='<grid-url>',
options=chrome_options
)asyncwith driver.bidi_connection()as session:
cdpSession = session.session
await cdpSession.execute(devtools.emulation.set_geolocation_override(latitude=41.8781,longitude=-87.6298,accuracy=100))
driver.get("https://my-location.org/")
driver.quit()
usingSystem.Threading.Tasks;usingOpenQA.Selenium.Chrome;usingOpenQA.Selenium.DevTools;// Replace the version to match the Chrome versionusingOpenQA.Selenium.DevTools.V87.Emulation;namespacedotnet_test{classProgram{publicstaticvoidMain(string[] args){GeoLocation().GetAwaiter().GetResult();}publicstaticasyncTaskGeoLocation(){ChromeOptions chromeOptions =newChromeOptions();RemoteWebDriver driver =newRemoteWebDriver(newUri("<grid-url>"), chromeOptions);DevToolsSession devToolsSession = driver.CreateDevToolsSession();var geoLocationOverrideCommandSettings =newSetGeolocationOverrideCommandSettings();
geoLocationOverrideCommandSettings.Latitude =51.507351;
geoLocationOverrideCommandSettings.Longitude =-0.127758;
geoLocationOverrideCommandSettings.Accuracy =1;await devToolsSession
.GetVersionSpecificDomains<OpenQA.Selenium.DevTools.V87.DevToolsSessionDomains>().Emulation
.SetGeolocationOverride(geoLocationOverrideCommandSettings);
driver.Url ="https://my-location.org/";}}}
driver =Selenium::WebDriver.for(:remote,:url=>"<grid-url>",:capabilities=>:chrome)begin# Latitude and longitude of Tokyo, Japan
coordinates ={ latitude:35.689487,
longitude:139.691706,
accuracy:100}
devToolsSession = driver.devtools
devToolsSession.send_cmd('Emulation.setGeolocationOverride', coordinates)
driver.get 'https://my-location.org/'
puts res
ensure
driver.quit
end
const webdriver =require('selenium-webdriver');constBROWSER_NAME= webdriver.Browser.CHROME;asyncfunctiongetDriver(){returnnewwebdriver.Builder().usingServer('<grid-url>').forBrowser(BROWSER_NAME).build();}asyncfunctionexecuteCDPCommands(){let driver =awaitgetDriver();await driver.get("<your site url>");const cdpConnection =await driver.createCDPConnection('page');//Latitude and longitude of Tokyo, Japanconst coordinates ={latitude:35.689487,longitude:139.691706,accuracy:100,};await cdpConnection.execute("Emulation.setGeolocationOverride",
coordinates
);await driver.quit();}executeCDPCommands();
import org.openqa.selenium.WebDriver
import org.openqa.selenium.chrome.ChromeOptions
import org.openqa.selenium.devtools.HasDevTools
// Replace the version to match the Chrome versionimport org.openqa.selenium.devtools.v91.emulation.Emulation
import org.openqa.selenium.remote.Augmenter
import org.openqa.selenium.remote.RemoteWebDriver
import java.net.URL
import java.util.Optional
funmain(){val chromeOptions =ChromeOptions()var driver: WebDriver =RemoteWebDriver(URL("<grid-url>"), chromeOptions)
driver =Augmenter().augment(driver)val devTools =(driver as HasDevTools).devTools
devTools.createSession()
devTools.send(
Emulation.setGeolocationOverride(
Optional.of(52.5043),
Optional.of(13.4501),
Optional.of(1)))
driver["https://my-location.org/"]
driver.quit()}
from selenium import webdriver
driver = webdriver.Chrome()
driver.get('https://www.duckduckgo.com')
driver.execute_cdp_cmd('Performance.enable',{})
t = driver.execute_cdp_cmd('Performance.getMetrics',{})print(t)
driver.quit()
// File must contain the following using statementsusingOpenQA.Selenium;usingOpenQA.Selenium.Chrome;usingOpenQA.Selenium.DevTools;// We must use a version-specific set of domainsusingOpenQA.Selenium.DevTools.V94.Performance;publicasyncTaskPerformanceMetricsExample(){IWebDriver driver =newChromeDriver();IDevTools devTools = driver asIDevTools;DevToolsSession session = devTools.GetDevToolsSession();await session.SendCommand<EnableCommandSettings>(newEnableCommandSettings());var metricsResponse =await session.SendCommand<GetMetricsCommandSettings, GetMetricsCommandResponse>(newGetMetricsCommandSettings());
driver.Navigate().GoToUrl("http://www.google.com");
driver.Quit();var metrics = metricsResponse.Metrics;foreach(Metric metric in metrics){
Console.WriteLine("{0} = {1}", metric.Name, metric.Value);}}
await driver.get("https://www.duckduckgo.com");await driver.sendAndGetDevToolsCommand('Performance.enable')let result =await driver.sendAndGetDevToolsCommand('Performance.getMetrics')
console.log(result)await driver.quit();
val driver =ChromeDriver()val devTools = driver.devTools
devTools.createSession()
devTools.send(Performance.enable(Optional.empty()))val metricList: List<Metric>= devTools.send(Performance.getMetrics())
driver["https://google.com"]
driver.quit()for(m in metricList){println(m.name.toString()+" = "+ m.value)}
2 - BiDirectional API (CDP implementation)
Page being translated from
English to Chinese. Do you speak Chinese? Help us to translate
it by sending us pull requests!
The following list of APIs will be growing as the Selenium
project works through supporting real world use cases. If there
is additional functionality you’d like to see, please raise a
feature request.
Register Basic Auth
Some applications make use of browser authentication to secure pages.
With Selenium, you can automate the input of basic auth credentials whenever they arise.
Predicate<URI> uriPredicate = uri -> uri.getHost().contains("your-domain.com");((HasAuthentication) driver).register(uriPredicate,UsernameAndPassword.of("admin","password"));
driver.get("https://your-domain.com/login");
val uriPredicate = Predicate { uri: URI ->
uri.host.contains("your-domain.com")}(driver as HasAuthentication).register(uriPredicate, UsernameAndPassword.of("admin","password"))
driver.get("https://your-domain.com/login")
Mutation Observation
Mutation Observation is the ability to capture events via
WebDriver BiDi when there are DOM mutations on a specific
element in the DOM.
val driver =ChromeDriver()val interceptor = new NetworkInterceptor(
driver,
Route.matching(req ->true).to(()-> req -> new HttpResponse().setStatus(200).addHeader("Content-Type", MediaType.HTML_UTF_8.toString()).setContent(utf8String("Creamy, delicious cheese!"))))
driver.get(appServer.whereIs("/cheese"))
String source = driver.getPageSource()
3 - BiDirectional API (W3C compliant)
The following list of APIs will be growing as the WebDriver BiDirectional Protocol grows
and browser vendors implement the same.
Additionally, Selenium will try to support real-world use cases that internally use a combination of W3C BiDi protocol APIs.
If there is additional functionality you’d like to see, please raise a
feature request.
3.1 - Browsing Context
Page being translated from
English to Chinese. Do you speak Chinese? Help us to translate
it by sending us pull requests!
This section contains the APIs related to browsing context commands.
A reference browsing context is a top-level browsing context.
The API allows to pass the reference browsing context, which is used to create a new window. The implementation is operating system specific.
A reference browsing context is a top-level browsing context.
The API allows to pass the reference browsing context, which is used to create a new tab. The implementation is operating system specific.
Provides a tree of all browsing contexts descending from the parent browsing context, including the parent browsing context upto the depth value passed.