diff --git a/documentation/_print/index.html b/documentation/_print/index.html index b70aae416911..659595fad370 100644 --- a/documentation/_print/index.html +++ b/documentation/_print/index.html @@ -253,13 +253,13 @@ testImplementation 'org.junit.jupiter:junit-jupiter-engine:5.11.0'
View full example on GitHub

The minimum supported Python version for each Selenium version can be found in Supported Python Versions on PyPi

There are a couple different ways to install Selenium.

Pip

pip install selenium
-

Download

Alternatively you can download the PyPI source archive +


Download

Alternatively you can download the PyPI source archive (selenium-x.x.x.tar.gz) and install it using setup.py:

python setup.py install
-

Require in project

To use it in a project, add it to the requirements.txt file:

selenium==4.23.1
+

Require in project

To use it in a project, add it to the requirements.txt file:

selenium==4.23.1
View full example on GitHub

A list of all supported frameworks for each version of Selenium is available on Nuget

There are a few options for installing Selenium.

Packet Manager

Install-Package Selenium.WebDriver
-

.NET CLI

dotnet add package Selenium.WebDriver
-

CSProj

in the project’s csproj file, specify the dependency as a PackageReference in ItemGroup:

      <PackageReference Include="Selenium.WebDriver" Version="4.23.0" />
+

.NET CLI

dotnet add package Selenium.WebDriver
+

CSProj

in the project’s csproj file, specify the dependency as a PackageReference in ItemGroup:

      <PackageReference Include="Selenium.WebDriver" Version="4.23.0" />
View full example on GitHub

Additional considerations

Further items of note for using Visual Studio Code (vscode) and C#

Install the compatible .NET SDK as per the section above. Also install the vscode extensions (Ctrl-Shift-X) for C# and NuGet. Follow the instruction here @@ -278,10 +278,10 @@ Press Enter and select the version. Now you can use the examples in the documentation related to C# with vscode.

You can see the minimum required version of Ruby for any given Selenium version on rubygems.org

Selenium can be installed two different ways.

Install manually

gem install selenium-webdriver
-

Add to project’s gemfile

gem 'selenium-devtools', '= 0.127.0'
+

Add to project’s gemfile

gem 'selenium-devtools', '= 0.127.0'
View full example on GitHub

You can find the minimum required version of Node for any given version of Selenium in the Node Support Policy section on npmjs

Selenium is typically installed using npm.

Install locally

npm install selenium-webdriver
-

Add to project

In your project’s package.json, add requirement to dependencies:

        "mocha": "10.7.3"
+

Add to project

In your project’s package.json, add requirement to dependencies:

        "mocha": "10.7.3"
View full example on GitHub
Use the Java bindings for Kotlin.

Next Step

Create your first Selenium script

2.1.2 - Write your first Selenium script

Step-by-step instructions for constructing a Selenium script

Once you have Selenium installed, you’re ready to write Selenium code.

Eight Basic Components

Everything Selenium does is send the browser commands to do something or send requests for information. Most of what you’ll do with Selenium is a combination of these basic commands

Click on the link to “View full example on GitHub” to see the code in context.

1. Start the session

For more details on starting a session read our documentation on driver sessions

		String title = driver.getTitle();
 		assertEquals("Web form", title);
    title = driver.title
-    assert title == "Web form"
            var title = driver.Title;
             Assert.AreEqual("Web form", title);
    title = @driver.title
@@ -473,9 +473,9 @@
 View full example on GitHub

Set Up

def setup():
     driver = webdriver.Chrome()
     driver.get("https://www.selenium.dev/selenium/web/web-form.html")
-    return driver

Tear Down

def teardown(driver):
-    driver.quit()

Java and C#
WebDriver, WebElement and ShadowRoot classes all implement a SearchContext interface, which is considered a role-based interface. Role-based interfaces allow you to determine whether a particular driver implementation supports a given feature. These interfaces are clearly defined and try -to adhere to having only a single role of responsibility.

Optimized locator

A nested lookup might not be the most effective location strategy since it requires two +to adhere to having only a single role of responsibility.

Evaluating the Shadow DOM

The Shadow DOM is an encapsulated DOM tree hidden inside an element. +With the release of v96 in Chromium Browsers, Selenium can now allow you to access this tree with +easy-to-use shadow root methods. NOTE: These methods require Selenium 4.0 or greater.

Move Code

WebElement shadowHost = driver.findElement(By.cssSelector("#shadow_host"));
+SearchContext shadowRoot = shadowHost.getShadowRoot();
+WebElement shadowContent = shadowRoot.findElement(By.cssSelector("#shadow_content"));
shadow_host = driver.find_element(By.CSS_SELECTOR, '#shadow_host')
+shadow_root = shadow_host.shadow_root
+shadow_content = shadow_root.find_element(By.CSS_SELECTOR, '#shadow_content')
var shadowHost = _driver.FindElement(By.CssSelector("#shadow_host"));
+var shadowRoot = shadowHost.GetShadowRoot();
+var shadowContent = shadowRoot.FindElement(By.CssSelector("#shadow_content"));
shadow_host = @driver.find_element(css: '#shadow_host') +shadow_root = shadow_host.shadow_root +shadow_content = shadow_root.find_element(css: '#shadow_content')

Optimized locator

A nested lookup might not be the most effective location strategy since it requires two separate commands to be issued to the browser.

To improve the performance slightly, we can use either CSS or XPath to find this element in a single command. See the Locator strategy suggestions in our -Encouraged test practices section.

For this example, we’ll use a CSS Selector:

Move Code

WebElement fruit = driver.findElement(By.cssSelector("#fruits .tomatoes"));
-  
fruit = driver.find_element(By.CSS_SELECTOR,"#fruits .tomatoes")
-  
var fruit = driver.FindElement(By.CssSelector("#fruits .tomatoes"));
-  
      fruit = driver.find_element(css: '#fruits .tomatoes')
const fruit = await driver.findElement(By.css('#fruits .tomatoes'));
-  
-
val fruit = driver.findElement(By.cssSelector("#fruits .tomatoes"))
-  

All matching elements

There are several use cases for needing to get references to all elements that match a locator, rather -than just the first one. The plural find elements methods return a collection of element references. -If there are no matches, an empty list is returned. In this case, -references to all fruits and vegetable list items will be returned in a collection.

Move Code

List<WebElement> plants = driver.findElements(By.tagName("li"));
-  
plants = driver.find_elements(By.TAG_NAME, "li")
-  
IReadOnlyList<IWebElement> plants = driver.FindElements(By.TagName("li"));
-  
      plants = driver.find_elements(tag_name: 'li')
const plants = await driver.findElements(By.tagName('li'));
+Kotlin
WebElement fruit = driver.findElement(By.cssSelector("#fruits .tomatoes"));
+  
fruit = driver.find_element(By.CSS_SELECTOR,"#fruits .tomatoes")
+  
var fruit = driver.FindElement(By.CssSelector("#fruits .tomatoes"));
+  
      fruit = driver.find_element(css: '#fruits .tomatoes')
const fruit = await driver.findElement(By.css('#fruits .tomatoes'));
   
-
val plants: List<WebElement> = driver.findElements(By.tagName("li"))
-  

Get element

Often you get a collection of elements but want to work with a specific element, which means you -need to iterate over the collection and identify the one you want.

Move Code

val fruit = driver.findElement(By.cssSelector("#fruits .tomatoes"))
+  

All matching elements

There are several use cases for needing to get references to all elements that match a locator, rather +than just the first one. The plural find elements methods return a collection of element references. +If there are no matches, an empty list is returned. In this case, +references to all fruits and vegetable list items will be returned in a collection.

Move Code

List<WebElement> elements = driver.findElements(By.tagName("li"));
+Kotlin
List<WebElement> plants = driver.findElements(By.tagName("li"));
+  
plants = driver.find_elements(By.TAG_NAME, "li")
+  
IReadOnlyList<IWebElement> plants = driver.FindElements(By.TagName("li"));
+  
      plants = driver.find_elements(tag_name: 'li')
const plants = await driver.findElements(By.tagName('li'));
+  
+
val plants: List<WebElement> = driver.findElements(By.tagName("li"))
+  

Get element

Often you get a collection of elements but want to work with a specific element, which means you +need to iterate over the collection and identify the one you want.

Move Code

List<WebElement> elements = driver.findElements(By.tagName("li"));
 
 for (WebElement element : elements) {
     System.out.println("Paragraph text:" + element.getText());
 }
-  
from selenium import webdriver
+  
from selenium import webdriver
 from selenium.webdriver.common.by import By
 
 driver = webdriver.Firefox()
@@ -2900,7 +2914,7 @@
 
 for e in elements:
     print(e.text)
-  
using OpenQA.Selenium;
+  
using OpenQA.Selenium;
 using OpenQA.Selenium.Firefox;
 using System.Collections.Generic;
 
@@ -2924,9 +2938,9 @@
   }
  }
 }
-  
      elements = driver.find_elements(:tag_name,'p')
+  
      elements = driver.find_elements(:tag_name,'p')
          elements.each { |e| puts e.text }
const {Builder, By} = require('selenium-webdriver');
+View full example on GitHub
const {Builder, By} = require('selenium-webdriver');
 (async function example() {
     let driver = await new Builder().forBrowser('firefox').build();
     try {
@@ -2944,7 +2958,7 @@
     }
 })();
   
-
import org.openqa.selenium.By
+
import org.openqa.selenium.By
 import org.openqa.selenium.firefox.FirefoxDriver
 
 fun main() {
@@ -2961,13 +2975,13 @@
     }
 }
   

Find Elements From Element

It is used to find the list of matching child WebElements within the context of parent element. -To achieve this, the parent WebElement is chained with ‘findElements’ to access child elements

Move Code

  import org.openqa.selenium.By;
+To achieve this, the parent WebElement is chained with ‘findElements’ to access child elements

Move Code

  import org.openqa.selenium.By;
   import org.openqa.selenium.WebDriver;
   import org.openqa.selenium.WebElement;
   import org.openqa.selenium.chrome.ChromeDriver;
@@ -2992,7 +3006,7 @@
           }
       }
   }
-  
from selenium import webdriver
+  
from selenium import webdriver
 from selenium.webdriver.common.by import By
 
 driver = webdriver.Chrome()
@@ -3017,7 +3031,7 @@
 elements  = driver.find_elements(By.XPATH, './/li')
 for e in elements:
     print(e.text)
-  
using OpenQA.Selenium;
+  
using OpenQA.Selenium;
 using OpenQA.Selenium.Chrome;
 using System.Collections.Generic;
 
@@ -3042,10 +3056,10 @@
   }
  }
 }
-  
      element = driver.find_element(:tag_name,'div')
+  
      element = driver.find_element(:tag_name,'div')
          elements = element.find_elements(:tag_name,'p')
          elements.each { |e| puts e.text }
  const {Builder, By} = require('selenium-webdriver');
+View full example on GitHub
  const {Builder, By} = require('selenium-webdriver');
 
   (async function example() {
       let driver = new Builder()
@@ -3064,7 +3078,7 @@
       }
   })();
   
-
  import org.openqa.selenium.By
+
  import org.openqa.selenium.By
   import org.openqa.selenium.chrome.ChromeDriver
 
   fun main() {
@@ -3084,13 +3098,13 @@
           driver.quit()
       }
   }
-  

Get Active Element

It is used to track (or) find DOM element which has the focus in the current browsing context.

Move Code

  import org.openqa.selenium.*;
+  

Get Active Element

It is used to track (or) find DOM element which has the focus in the current browsing context.

Move Code

  import org.openqa.selenium.*;
   import org.openqa.selenium.chrome.ChromeDriver;
 
   public class activeElementTest {
@@ -3108,7 +3122,7 @@
       }
     }
   }
-  
  from selenium import webdriver
+  
  from selenium import webdriver
   from selenium.webdriver.common.by import By
 
   driver = webdriver.Chrome()
@@ -3118,7 +3132,7 @@
     # Get attribute of current active element
   attr = driver.switch_to.active_element.get_attribute("title")
   print(attr)
-  
    using OpenQA.Selenium;
+  
    using OpenQA.Selenium;
     using OpenQA.Selenium.Chrome;
 
     namespace ActiveElement {
@@ -3139,9 +3153,9 @@
       }
      }
     }
-  
      driver.find_element(css: '[name="q"]').send_keys('webElement')
+  
      driver.find_element(css: '[name="q"]').send_keys('webElement')
         attr = driver.switch_to.active_element.attribute('title')
  const {Builder, By} = require('selenium-webdriver');
+View full example on GitHub
  const {Builder, By} = require('selenium-webdriver');
 
   (async function example() {
       let driver = await new Builder().forBrowser('chrome').build();
@@ -3153,7 +3167,7 @@
       console.log(`${attr}`)
   })();
   
-
  import org.openqa.selenium.By
+
  import org.openqa.selenium.By
   import org.openqa.selenium.chrome.ChromeDriver
 
   fun main() {
@@ -13943,7 +13957,7 @@
 No patent liability is assumed with respect
 to the use of the information contained herein.

Attributions

Selenium Main Repository

-5320 commits
+5321 commits
3352 commits
@@ -14471,7 +14485,9 @@ 17 commits
-15 commits
+15 commits
+ +13 commits
@@ -14481,8 +14497,6 @@ 10 commits
-8 commits
- 8 commits
7 commits
diff --git a/documentation/about/_print/index.html b/documentation/about/_print/index.html index 869b5f6ee5cb..099b320f497d 100644 --- a/documentation/about/_print/index.html +++ b/documentation/about/_print/index.html @@ -40,7 +40,7 @@ No patent liability is assumed with respect to the use of the information contained herein.

Attributions

Selenium Main Repository

-5320 commits
+5321 commits
3352 commits
@@ -568,7 +568,9 @@ 17 commits
-15 commits
+15 commits
+ +13 commits
@@ -578,8 +580,6 @@ 10 commits
-8 commits
- 8 commits
7 commits
diff --git a/documentation/about/copyright/index.html b/documentation/about/copyright/index.html index 375d0f480bbb..2f58c4c1f99f 100644 --- a/documentation/about/copyright/index.html +++ b/documentation/about/copyright/index.html @@ -26,7 +26,7 @@ No patent liability is assumed with respect to the use of the information contained herein.

Attributions

Selenium Main Repository

-5320 commits
+5321 commits
3352 commits
@@ -554,7 +554,9 @@ 17 commits
-15 commits
+15 commits
+ +13 commits
@@ -564,8 +566,6 @@ 10 commits
-8 commits
- 8 commits
7 commits
diff --git a/documentation/webdriver/_print/index.html b/documentation/webdriver/_print/index.html index c42948d1d575..378430f81d19 100644 --- a/documentation/webdriver/_print/index.html +++ b/documentation/webdriver/_print/index.html @@ -54,13 +54,13 @@ testImplementation 'org.junit.jupiter:junit-jupiter-engine:5.11.0'

The minimum supported Python version for each Selenium version can be found in Supported Python Versions on PyPi

There are a couple different ways to install Selenium.

Pip

pip install selenium
-

Download

Alternatively you can download the PyPI source archive +


Download

Alternatively you can download the PyPI source archive (selenium-x.x.x.tar.gz) and install it using setup.py:

python setup.py install
-

Require in project

To use it in a project, add it to the requirements.txt file:

selenium==4.23.1

Require in project

To use it in a project, add it to the requirements.txt file:

selenium==4.23.1

A list of all supported frameworks for each version of Selenium is available on Nuget

There are a few options for installing Selenium.

Packet Manager

Install-Package Selenium.WebDriver
-

.NET CLI

dotnet add package Selenium.WebDriver
-

CSProj

in the project’s csproj file, specify the dependency as a PackageReference in ItemGroup:

      <PackageReference Include="Selenium.WebDriver" Version="4.23.0" />

.NET CLI

dotnet add package Selenium.WebDriver
+

CSProj

in the project’s csproj file, specify the dependency as a PackageReference in ItemGroup:

      <PackageReference Include="Selenium.WebDriver" Version="4.23.0" />

Additional considerations

Further items of note for using Visual Studio Code (vscode) and C#

Install the compatible .NET SDK as per the section above. Also install the vscode extensions (Ctrl-Shift-X) for C# and NuGet. Follow the instruction here @@ -79,10 +79,10 @@ Press Enter and select the version. Now you can use the examples in the documentation related to C# with vscode.

You can see the minimum required version of Ruby for any given Selenium version on rubygems.org

Selenium can be installed two different ways.

Install manually

gem install selenium-webdriver
-

Add to project’s gemfile

gem 'selenium-devtools', '= 0.127.0'

Add to project’s gemfile

gem 'selenium-devtools', '= 0.127.0'

You can find the minimum required version of Node for any given version of Selenium in the Node Support Policy section on npmjs

Selenium is typically installed using npm.

Install locally

npm install selenium-webdriver
-

Add to project

In your project’s package.json, add requirement to dependencies:

        "mocha": "10.7.3"

Add to project

In your project’s package.json, add requirement to dependencies:

        "mocha": "10.7.3"
Use the Java bindings for Kotlin.

Next Step

Create your first Selenium script

1.2 - Write your first Selenium script

Step-by-step instructions for constructing a Selenium script

Once you have Selenium installed, you’re ready to write Selenium code.

Eight Basic Components

Everything Selenium does is send the browser commands to do something or send requests for information. Most of what you’ll do with Selenium is a combination of these basic commands

Click on the link to “View full example on GitHub” to see the code in context.

1. Start the session

For more details on starting a session read our documentation on driver sessions

		String title = driver.getTitle();
 		assertEquals("Web form", title);
    title = driver.title
-    assert title == "Web form"
            var title = driver.Title;
             Assert.AreEqual("Web form", title);
    title = @driver.title
@@ -274,9 +274,9 @@
 View full example on GitHub

Set Up

def setup():
     driver = webdriver.Chrome()
     driver.get("https://www.selenium.dev/selenium/web/web-form.html")
-    return driver

Tear Down

def teardown(driver):
-    driver.quit()

Java and C#
WebDriver, WebElement and ShadowRoot classes all implement a SearchContext interface, which is considered a role-based interface. Role-based interfaces allow you to determine whether a particular driver implementation supports a given feature. These interfaces are clearly defined and try -to adhere to having only a single role of responsibility.

Optimized locator

A nested lookup might not be the most effective location strategy since it requires two +to adhere to having only a single role of responsibility.

Evaluating the Shadow DOM

The Shadow DOM is an encapsulated DOM tree hidden inside an element. +With the release of v96 in Chromium Browsers, Selenium can now allow you to access this tree with +easy-to-use shadow root methods. NOTE: These methods require Selenium 4.0 or greater.

Move Code

WebElement shadowHost = driver.findElement(By.cssSelector("#shadow_host"));
+SearchContext shadowRoot = shadowHost.getShadowRoot();
+WebElement shadowContent = shadowRoot.findElement(By.cssSelector("#shadow_content"));
shadow_host = driver.find_element(By.CSS_SELECTOR, '#shadow_host')
+shadow_root = shadow_host.shadow_root
+shadow_content = shadow_root.find_element(By.CSS_SELECTOR, '#shadow_content')
var shadowHost = _driver.FindElement(By.CssSelector("#shadow_host"));
+var shadowRoot = shadowHost.GetShadowRoot();
+var shadowContent = shadowRoot.FindElement(By.CssSelector("#shadow_content"));
shadow_host = @driver.find_element(css: '#shadow_host') +shadow_root = shadow_host.shadow_root +shadow_content = shadow_root.find_element(css: '#shadow_content')

Optimized locator

A nested lookup might not be the most effective location strategy since it requires two separate commands to be issued to the browser.

To improve the performance slightly, we can use either CSS or XPath to find this element in a single command. See the Locator strategy suggestions in our -Encouraged test practices section.

For this example, we’ll use a CSS Selector:

Move Code

WebElement fruit = driver.findElement(By.cssSelector("#fruits .tomatoes"));
-  
fruit = driver.find_element(By.CSS_SELECTOR,"#fruits .tomatoes")
-  
var fruit = driver.FindElement(By.CssSelector("#fruits .tomatoes"));
-  
      fruit = driver.find_element(css: '#fruits .tomatoes')
const fruit = await driver.findElement(By.css('#fruits .tomatoes'));
-  
-
val fruit = driver.findElement(By.cssSelector("#fruits .tomatoes"))
-  

All matching elements

There are several use cases for needing to get references to all elements that match a locator, rather -than just the first one. The plural find elements methods return a collection of element references. -If there are no matches, an empty list is returned. In this case, -references to all fruits and vegetable list items will be returned in a collection.

Move Code

List<WebElement> plants = driver.findElements(By.tagName("li"));
-  
plants = driver.find_elements(By.TAG_NAME, "li")
-  
IReadOnlyList<IWebElement> plants = driver.FindElements(By.TagName("li"));
-  
      plants = driver.find_elements(tag_name: 'li')
const plants = await driver.findElements(By.tagName('li'));
+Kotlin
WebElement fruit = driver.findElement(By.cssSelector("#fruits .tomatoes"));
+  
fruit = driver.find_element(By.CSS_SELECTOR,"#fruits .tomatoes")
+  
var fruit = driver.FindElement(By.CssSelector("#fruits .tomatoes"));
+  
      fruit = driver.find_element(css: '#fruits .tomatoes')
const fruit = await driver.findElement(By.css('#fruits .tomatoes'));
   
-
val plants: List<WebElement> = driver.findElements(By.tagName("li"))
-  

Get element

Often you get a collection of elements but want to work with a specific element, which means you -need to iterate over the collection and identify the one you want.

Move Code

val fruit = driver.findElement(By.cssSelector("#fruits .tomatoes"))
+  

All matching elements

There are several use cases for needing to get references to all elements that match a locator, rather +than just the first one. The plural find elements methods return a collection of element references. +If there are no matches, an empty list is returned. In this case, +references to all fruits and vegetable list items will be returned in a collection.

Move Code

List<WebElement> elements = driver.findElements(By.tagName("li"));
+Kotlin
List<WebElement> plants = driver.findElements(By.tagName("li"));
+  
plants = driver.find_elements(By.TAG_NAME, "li")
+  
IReadOnlyList<IWebElement> plants = driver.FindElements(By.TagName("li"));
+  
      plants = driver.find_elements(tag_name: 'li')
const plants = await driver.findElements(By.tagName('li'));
+  
+
val plants: List<WebElement> = driver.findElements(By.tagName("li"))
+  

Get element

Often you get a collection of elements but want to work with a specific element, which means you +need to iterate over the collection and identify the one you want.

Move Code

List<WebElement> elements = driver.findElements(By.tagName("li"));
 
 for (WebElement element : elements) {
     System.out.println("Paragraph text:" + element.getText());
 }
-  
from selenium import webdriver
+  
from selenium import webdriver
 from selenium.webdriver.common.by import By
 
 driver = webdriver.Firefox()
@@ -2701,7 +2715,7 @@
 
 for e in elements:
     print(e.text)
-  
using OpenQA.Selenium;
+  
using OpenQA.Selenium;
 using OpenQA.Selenium.Firefox;
 using System.Collections.Generic;
 
@@ -2725,9 +2739,9 @@
   }
  }
 }
-  
      elements = driver.find_elements(:tag_name,'p')
+  
      elements = driver.find_elements(:tag_name,'p')
          elements.each { |e| puts e.text }
const {Builder, By} = require('selenium-webdriver');
+View full example on GitHub
const {Builder, By} = require('selenium-webdriver');
 (async function example() {
     let driver = await new Builder().forBrowser('firefox').build();
     try {
@@ -2745,7 +2759,7 @@
     }
 })();
   
-
import org.openqa.selenium.By
+
import org.openqa.selenium.By
 import org.openqa.selenium.firefox.FirefoxDriver
 
 fun main() {
@@ -2762,13 +2776,13 @@
     }
 }
   

Find Elements From Element

It is used to find the list of matching child WebElements within the context of parent element. -To achieve this, the parent WebElement is chained with ‘findElements’ to access child elements

Move Code

  import org.openqa.selenium.By;
+To achieve this, the parent WebElement is chained with ‘findElements’ to access child elements

Move Code

  import org.openqa.selenium.By;
   import org.openqa.selenium.WebDriver;
   import org.openqa.selenium.WebElement;
   import org.openqa.selenium.chrome.ChromeDriver;
@@ -2793,7 +2807,7 @@
           }
       }
   }
-  
from selenium import webdriver
+  
from selenium import webdriver
 from selenium.webdriver.common.by import By
 
 driver = webdriver.Chrome()
@@ -2818,7 +2832,7 @@
 elements  = driver.find_elements(By.XPATH, './/li')
 for e in elements:
     print(e.text)
-  
using OpenQA.Selenium;
+  
using OpenQA.Selenium;
 using OpenQA.Selenium.Chrome;
 using System.Collections.Generic;
 
@@ -2843,10 +2857,10 @@
   }
  }
 }
-  
      element = driver.find_element(:tag_name,'div')
+  
      element = driver.find_element(:tag_name,'div')
          elements = element.find_elements(:tag_name,'p')
          elements.each { |e| puts e.text }
  const {Builder, By} = require('selenium-webdriver');
+View full example on GitHub
  const {Builder, By} = require('selenium-webdriver');
 
   (async function example() {
       let driver = new Builder()
@@ -2865,7 +2879,7 @@
       }
   })();
   
-
  import org.openqa.selenium.By
+
  import org.openqa.selenium.By
   import org.openqa.selenium.chrome.ChromeDriver
 
   fun main() {
@@ -2885,13 +2899,13 @@
           driver.quit()
       }
   }
-  

Get Active Element

It is used to track (or) find DOM element which has the focus in the current browsing context.

Move Code

  import org.openqa.selenium.*;
+  

Get Active Element

It is used to track (or) find DOM element which has the focus in the current browsing context.

Move Code

  import org.openqa.selenium.*;
   import org.openqa.selenium.chrome.ChromeDriver;
 
   public class activeElementTest {
@@ -2909,7 +2923,7 @@
       }
     }
   }
-  
  from selenium import webdriver
+  
  from selenium import webdriver
   from selenium.webdriver.common.by import By
 
   driver = webdriver.Chrome()
@@ -2919,7 +2933,7 @@
     # Get attribute of current active element
   attr = driver.switch_to.active_element.get_attribute("title")
   print(attr)
-  
    using OpenQA.Selenium;
+  
    using OpenQA.Selenium;
     using OpenQA.Selenium.Chrome;
 
     namespace ActiveElement {
@@ -2940,9 +2954,9 @@
       }
      }
     }
-  
      driver.find_element(css: '[name="q"]').send_keys('webElement')
+  
      driver.find_element(css: '[name="q"]').send_keys('webElement')
         attr = driver.switch_to.active_element.attribute('title')
  const {Builder, By} = require('selenium-webdriver');
+View full example on GitHub
  const {Builder, By} = require('selenium-webdriver');
 
   (async function example() {
       let driver = await new Builder().forBrowser('chrome').build();
@@ -2954,7 +2968,7 @@
       console.log(`${attr}`)
   })();
   
-
  import org.openqa.selenium.By
+
  import org.openqa.selenium.By
   import org.openqa.selenium.chrome.ChromeDriver
 
   fun main() {
diff --git a/documentation/webdriver/elements/_print/index.html b/documentation/webdriver/elements/_print/index.html
index 1337a23166ed..361b134c15b3 100644
--- a/documentation/webdriver/elements/_print/index.html
+++ b/documentation/webdriver/elements/_print/index.html
@@ -385,51 +385,67 @@
   

Java and C#
WebDriver, WebElement and ShadowRoot classes all implement a SearchContext interface, which is considered a role-based interface. Role-based interfaces allow you to determine whether a particular driver implementation supports a given feature. These interfaces are clearly defined and try -to adhere to having only a single role of responsibility.

Optimized locator

A nested lookup might not be the most effective location strategy since it requires two +to adhere to having only a single role of responsibility.

Evaluating the Shadow DOM

The Shadow DOM is an encapsulated DOM tree hidden inside an element. +With the release of v96 in Chromium Browsers, Selenium can now allow you to access this tree with +easy-to-use shadow root methods. NOTE: These methods require Selenium 4.0 or greater.

Move Code

WebElement shadowHost = driver.findElement(By.cssSelector("#shadow_host"));
+SearchContext shadowRoot = shadowHost.getShadowRoot();
+WebElement shadowContent = shadowRoot.findElement(By.cssSelector("#shadow_content"));
shadow_host = driver.find_element(By.CSS_SELECTOR, '#shadow_host')
+shadow_root = shadow_host.shadow_root
+shadow_content = shadow_root.find_element(By.CSS_SELECTOR, '#shadow_content')
var shadowHost = _driver.FindElement(By.CssSelector("#shadow_host"));
+var shadowRoot = shadowHost.GetShadowRoot();
+var shadowContent = shadowRoot.FindElement(By.CssSelector("#shadow_content"));
shadow_host = @driver.find_element(css: '#shadow_host') +shadow_root = shadow_host.shadow_root +shadow_content = shadow_root.find_element(css: '#shadow_content')

Optimized locator

A nested lookup might not be the most effective location strategy since it requires two separate commands to be issued to the browser.

To improve the performance slightly, we can use either CSS or XPath to find this element in a single command. See the Locator strategy suggestions in our -Encouraged test practices section.

For this example, we’ll use a CSS Selector:

Move Code

WebElement fruit = driver.findElement(By.cssSelector("#fruits .tomatoes"));
-  
fruit = driver.find_element(By.CSS_SELECTOR,"#fruits .tomatoes")
-  
var fruit = driver.FindElement(By.CssSelector("#fruits .tomatoes"));
-  
      fruit = driver.find_element(css: '#fruits .tomatoes')
const fruit = await driver.findElement(By.css('#fruits .tomatoes'));
-  
-
val fruit = driver.findElement(By.cssSelector("#fruits .tomatoes"))
-  

All matching elements

There are several use cases for needing to get references to all elements that match a locator, rather -than just the first one. The plural find elements methods return a collection of element references. -If there are no matches, an empty list is returned. In this case, -references to all fruits and vegetable list items will be returned in a collection.

Move Code

List<WebElement> plants = driver.findElements(By.tagName("li"));
-  
plants = driver.find_elements(By.TAG_NAME, "li")
-  
IReadOnlyList<IWebElement> plants = driver.FindElements(By.TagName("li"));
-  
      plants = driver.find_elements(tag_name: 'li')
const plants = await driver.findElements(By.tagName('li'));
+Kotlin
WebElement fruit = driver.findElement(By.cssSelector("#fruits .tomatoes"));
+  
fruit = driver.find_element(By.CSS_SELECTOR,"#fruits .tomatoes")
+  
var fruit = driver.FindElement(By.CssSelector("#fruits .tomatoes"));
+  
      fruit = driver.find_element(css: '#fruits .tomatoes')
const fruit = await driver.findElement(By.css('#fruits .tomatoes'));
   
-
val plants: List<WebElement> = driver.findElements(By.tagName("li"))
-  

Get element

Often you get a collection of elements but want to work with a specific element, which means you -need to iterate over the collection and identify the one you want.

Move Code

val fruit = driver.findElement(By.cssSelector("#fruits .tomatoes"))
+  

All matching elements

There are several use cases for needing to get references to all elements that match a locator, rather +than just the first one. The plural find elements methods return a collection of element references. +If there are no matches, an empty list is returned. In this case, +references to all fruits and vegetable list items will be returned in a collection.

Move Code

List<WebElement> elements = driver.findElements(By.tagName("li"));
+Kotlin
List<WebElement> plants = driver.findElements(By.tagName("li"));
+  
plants = driver.find_elements(By.TAG_NAME, "li")
+  
IReadOnlyList<IWebElement> plants = driver.FindElements(By.TagName("li"));
+  
      plants = driver.find_elements(tag_name: 'li')
const plants = await driver.findElements(By.tagName('li'));
+  
+
val plants: List<WebElement> = driver.findElements(By.tagName("li"))
+  

Get element

Often you get a collection of elements but want to work with a specific element, which means you +need to iterate over the collection and identify the one you want.

Move Code

List<WebElement> elements = driver.findElements(By.tagName("li"));
 
 for (WebElement element : elements) {
     System.out.println("Paragraph text:" + element.getText());
 }
-  
from selenium import webdriver
+  
from selenium import webdriver
 from selenium.webdriver.common.by import By
 
 driver = webdriver.Firefox()
@@ -442,7 +458,7 @@
 
 for e in elements:
     print(e.text)
-  
using OpenQA.Selenium;
+  
using OpenQA.Selenium;
 using OpenQA.Selenium.Firefox;
 using System.Collections.Generic;
 
@@ -466,9 +482,9 @@
   }
  }
 }
-  
      elements = driver.find_elements(:tag_name,'p')
+  
      elements = driver.find_elements(:tag_name,'p')
          elements.each { |e| puts e.text }
const {Builder, By} = require('selenium-webdriver');
+View full example on GitHub
const {Builder, By} = require('selenium-webdriver');
 (async function example() {
     let driver = await new Builder().forBrowser('firefox').build();
     try {
@@ -486,7 +502,7 @@
     }
 })();
   
-
import org.openqa.selenium.By
+
import org.openqa.selenium.By
 import org.openqa.selenium.firefox.FirefoxDriver
 
 fun main() {
@@ -503,13 +519,13 @@
     }
 }
   

Find Elements From Element

It is used to find the list of matching child WebElements within the context of parent element. -To achieve this, the parent WebElement is chained with ‘findElements’ to access child elements

Move Code

  import org.openqa.selenium.By;
+To achieve this, the parent WebElement is chained with ‘findElements’ to access child elements

Move Code

  import org.openqa.selenium.By;
   import org.openqa.selenium.WebDriver;
   import org.openqa.selenium.WebElement;
   import org.openqa.selenium.chrome.ChromeDriver;
@@ -534,7 +550,7 @@
           }
       }
   }
-  
from selenium import webdriver
+  
from selenium import webdriver
 from selenium.webdriver.common.by import By
 
 driver = webdriver.Chrome()
@@ -559,7 +575,7 @@
 elements  = driver.find_elements(By.XPATH, './/li')
 for e in elements:
     print(e.text)
-  
using OpenQA.Selenium;
+  
using OpenQA.Selenium;
 using OpenQA.Selenium.Chrome;
 using System.Collections.Generic;
 
@@ -584,10 +600,10 @@
   }
  }
 }
-  
      element = driver.find_element(:tag_name,'div')
+  
      element = driver.find_element(:tag_name,'div')
          elements = element.find_elements(:tag_name,'p')
          elements.each { |e| puts e.text }
  const {Builder, By} = require('selenium-webdriver');
+View full example on GitHub
  const {Builder, By} = require('selenium-webdriver');
 
   (async function example() {
       let driver = new Builder()
@@ -606,7 +622,7 @@
       }
   })();
   
-
  import org.openqa.selenium.By
+
  import org.openqa.selenium.By
   import org.openqa.selenium.chrome.ChromeDriver
 
   fun main() {
@@ -626,13 +642,13 @@
           driver.quit()
       }
   }
-  

Get Active Element

It is used to track (or) find DOM element which has the focus in the current browsing context.

Move Code

  import org.openqa.selenium.*;
+  

Get Active Element

It is used to track (or) find DOM element which has the focus in the current browsing context.

Move Code

  import org.openqa.selenium.*;
   import org.openqa.selenium.chrome.ChromeDriver;
 
   public class activeElementTest {
@@ -650,7 +666,7 @@
       }
     }
   }
-  
  from selenium import webdriver
+  
  from selenium import webdriver
   from selenium.webdriver.common.by import By
 
   driver = webdriver.Chrome()
@@ -660,7 +676,7 @@
     # Get attribute of current active element
   attr = driver.switch_to.active_element.get_attribute("title")
   print(attr)
-  
    using OpenQA.Selenium;
+  
    using OpenQA.Selenium;
     using OpenQA.Selenium.Chrome;
 
     namespace ActiveElement {
@@ -681,9 +697,9 @@
       }
      }
     }
-  
      driver.find_element(css: '[name="q"]').send_keys('webElement')
+  
      driver.find_element(css: '[name="q"]').send_keys('webElement')
         attr = driver.switch_to.active_element.attribute('title')
  const {Builder, By} = require('selenium-webdriver');
+View full example on GitHub
  const {Builder, By} = require('selenium-webdriver');
 
   (async function example() {
       let driver = await new Builder().forBrowser('chrome').build();
@@ -695,7 +711,7 @@
       console.log(`${attr}`)
   })();
   
-
  import org.openqa.selenium.By
+
  import org.openqa.selenium.By
   import org.openqa.selenium.chrome.ChromeDriver
 
   fun main() {
diff --git a/documentation/webdriver/elements/finders/index.html b/documentation/webdriver/elements/finders/index.html
index 377eff1637aa..01cf96d70857 100644
--- a/documentation/webdriver/elements/finders/index.html
+++ b/documentation/webdriver/elements/finders/index.html
@@ -1,7 +1,7 @@
 Finding web elements | Selenium
 

Finding web elements

Locating the elements based on the provided locator values.

One of the most fundamental aspects of using Selenium is obtaining element references to work with. + Print entire section



Finding web elements

Locating the elements based on the provided locator values.

One of the most fundamental aspects of using Selenium is obtaining element references to work with. Selenium offers a number of built-in locator strategies to uniquely identify an element. There are many ways to use the locators in very advanced scenarios. For the purposes of this documentation, let’s consider this HTML snippet:

<ol id="vegetables">
@@ -71,51 +71,67 @@
   

Java and C#
WebDriver, WebElement and ShadowRoot classes all implement a SearchContext interface, which is considered a role-based interface. Role-based interfaces allow you to determine whether a particular driver implementation supports a given feature. These interfaces are clearly defined and try -to adhere to having only a single role of responsibility.

Optimized locator

A nested lookup might not be the most effective location strategy since it requires two +to adhere to having only a single role of responsibility.

Evaluating the Shadow DOM

The Shadow DOM is an encapsulated DOM tree hidden inside an element. +With the release of v96 in Chromium Browsers, Selenium can now allow you to access this tree with +easy-to-use shadow root methods. NOTE: These methods require Selenium 4.0 or greater.

Move Code

WebElement shadowHost = driver.findElement(By.cssSelector("#shadow_host"));
+SearchContext shadowRoot = shadowHost.getShadowRoot();
+WebElement shadowContent = shadowRoot.findElement(By.cssSelector("#shadow_content"));
shadow_host = driver.find_element(By.CSS_SELECTOR, '#shadow_host')
+shadow_root = shadow_host.shadow_root
+shadow_content = shadow_root.find_element(By.CSS_SELECTOR, '#shadow_content')
var shadowHost = _driver.FindElement(By.CssSelector("#shadow_host"));
+var shadowRoot = shadowHost.GetShadowRoot();
+var shadowContent = shadowRoot.FindElement(By.CssSelector("#shadow_content"));
shadow_host = @driver.find_element(css: '#shadow_host') +shadow_root = shadow_host.shadow_root +shadow_content = shadow_root.find_element(css: '#shadow_content')

Optimized locator

A nested lookup might not be the most effective location strategy since it requires two separate commands to be issued to the browser.

To improve the performance slightly, we can use either CSS or XPath to find this element in a single command. See the Locator strategy suggestions in our -Encouraged test practices section.

For this example, we’ll use a CSS Selector:

Move Code

WebElement fruit = driver.findElement(By.cssSelector("#fruits .tomatoes"));
-  
fruit = driver.find_element(By.CSS_SELECTOR,"#fruits .tomatoes")
-  
var fruit = driver.FindElement(By.CssSelector("#fruits .tomatoes"));
-  
      fruit = driver.find_element(css: '#fruits .tomatoes')
const fruit = await driver.findElement(By.css('#fruits .tomatoes'));
-  
-
val fruit = driver.findElement(By.cssSelector("#fruits .tomatoes"))
-  

All matching elements

There are several use cases for needing to get references to all elements that match a locator, rather -than just the first one. The plural find elements methods return a collection of element references. -If there are no matches, an empty list is returned. In this case, -references to all fruits and vegetable list items will be returned in a collection.

Move Code

List<WebElement> plants = driver.findElements(By.tagName("li"));
-  
plants = driver.find_elements(By.TAG_NAME, "li")
-  
IReadOnlyList<IWebElement> plants = driver.FindElements(By.TagName("li"));
-  
      plants = driver.find_elements(tag_name: 'li')
const plants = await driver.findElements(By.tagName('li'));
+Kotlin
WebElement fruit = driver.findElement(By.cssSelector("#fruits .tomatoes"));
+  
fruit = driver.find_element(By.CSS_SELECTOR,"#fruits .tomatoes")
+  
var fruit = driver.FindElement(By.CssSelector("#fruits .tomatoes"));
+  
      fruit = driver.find_element(css: '#fruits .tomatoes')
const fruit = await driver.findElement(By.css('#fruits .tomatoes'));
   
-
val plants: List<WebElement> = driver.findElements(By.tagName("li"))
-  

Get element

Often you get a collection of elements but want to work with a specific element, which means you -need to iterate over the collection and identify the one you want.

Move Code

val fruit = driver.findElement(By.cssSelector("#fruits .tomatoes"))
+  

All matching elements

There are several use cases for needing to get references to all elements that match a locator, rather +than just the first one. The plural find elements methods return a collection of element references. +If there are no matches, an empty list is returned. In this case, +references to all fruits and vegetable list items will be returned in a collection.

Move Code

List<WebElement> elements = driver.findElements(By.tagName("li"));
+Kotlin
List<WebElement> plants = driver.findElements(By.tagName("li"));
+  
plants = driver.find_elements(By.TAG_NAME, "li")
+  
IReadOnlyList<IWebElement> plants = driver.FindElements(By.TagName("li"));
+  
      plants = driver.find_elements(tag_name: 'li')
const plants = await driver.findElements(By.tagName('li'));
+  
+
val plants: List<WebElement> = driver.findElements(By.tagName("li"))
+  

Get element

Often you get a collection of elements but want to work with a specific element, which means you +need to iterate over the collection and identify the one you want.

Move Code

List<WebElement> elements = driver.findElements(By.tagName("li"));
 
 for (WebElement element : elements) {
     System.out.println("Paragraph text:" + element.getText());
 }
-  
from selenium import webdriver
+  
from selenium import webdriver
 from selenium.webdriver.common.by import By
 
 driver = webdriver.Firefox()
@@ -128,7 +144,7 @@
 
 for e in elements:
     print(e.text)
-  
using OpenQA.Selenium;
+  
using OpenQA.Selenium;
 using OpenQA.Selenium.Firefox;
 using System.Collections.Generic;
 
@@ -152,9 +168,9 @@
   }
  }
 }
-  
      elements = driver.find_elements(:tag_name,'p')
+  
      elements = driver.find_elements(:tag_name,'p')
          elements.each { |e| puts e.text }
const {Builder, By} = require('selenium-webdriver');
+View full example on GitHub
const {Builder, By} = require('selenium-webdriver');
 (async function example() {
     let driver = await new Builder().forBrowser('firefox').build();
     try {
@@ -172,7 +188,7 @@
     }
 })();
   
-
import org.openqa.selenium.By
+
import org.openqa.selenium.By
 import org.openqa.selenium.firefox.FirefoxDriver
 
 fun main() {
@@ -189,13 +205,13 @@
     }
 }
   

Find Elements From Element

It is used to find the list of matching child WebElements within the context of parent element. -To achieve this, the parent WebElement is chained with ‘findElements’ to access child elements

Move Code

  import org.openqa.selenium.By;
+To achieve this, the parent WebElement is chained with ‘findElements’ to access child elements

Move Code

  import org.openqa.selenium.By;
   import org.openqa.selenium.WebDriver;
   import org.openqa.selenium.WebElement;
   import org.openqa.selenium.chrome.ChromeDriver;
@@ -220,7 +236,7 @@
           }
       }
   }
-  
from selenium import webdriver
+  
from selenium import webdriver
 from selenium.webdriver.common.by import By
 
 driver = webdriver.Chrome()
@@ -245,7 +261,7 @@
 elements  = driver.find_elements(By.XPATH, './/li')
 for e in elements:
     print(e.text)
-  
using OpenQA.Selenium;
+  
using OpenQA.Selenium;
 using OpenQA.Selenium.Chrome;
 using System.Collections.Generic;
 
@@ -270,10 +286,10 @@
   }
  }
 }
-  
      element = driver.find_element(:tag_name,'div')
+  
      element = driver.find_element(:tag_name,'div')
          elements = element.find_elements(:tag_name,'p')
          elements.each { |e| puts e.text }
  const {Builder, By} = require('selenium-webdriver');
+View full example on GitHub
  const {Builder, By} = require('selenium-webdriver');
 
   (async function example() {
       let driver = new Builder()
@@ -292,7 +308,7 @@
       }
   })();
   
-
  import org.openqa.selenium.By
+
  import org.openqa.selenium.By
   import org.openqa.selenium.chrome.ChromeDriver
 
   fun main() {
@@ -312,13 +328,13 @@
           driver.quit()
       }
   }
-  

Get Active Element

It is used to track (or) find DOM element which has the focus in the current browsing context.

Move Code

  import org.openqa.selenium.*;
+  

Get Active Element

It is used to track (or) find DOM element which has the focus in the current browsing context.

Move Code

  import org.openqa.selenium.*;
   import org.openqa.selenium.chrome.ChromeDriver;
 
   public class activeElementTest {
@@ -336,7 +352,7 @@
       }
     }
   }
-  
  from selenium import webdriver
+  
  from selenium import webdriver
   from selenium.webdriver.common.by import By
 
   driver = webdriver.Chrome()
@@ -346,7 +362,7 @@
     # Get attribute of current active element
   attr = driver.switch_to.active_element.get_attribute("title")
   print(attr)
-  
    using OpenQA.Selenium;
+  
    using OpenQA.Selenium;
     using OpenQA.Selenium.Chrome;
 
     namespace ActiveElement {
@@ -367,9 +383,9 @@
       }
      }
     }
-  
      driver.find_element(css: '[name="q"]').send_keys('webElement')
+  
      driver.find_element(css: '[name="q"]').send_keys('webElement')
         attr = driver.switch_to.active_element.attribute('title')
  const {Builder, By} = require('selenium-webdriver');
+View full example on GitHub
  const {Builder, By} = require('selenium-webdriver');
 
   (async function example() {
       let driver = await new Builder().forBrowser('chrome').build();
@@ -381,7 +397,7 @@
       console.log(`${attr}`)
   })();
   
-
  import org.openqa.selenium.By
+
  import org.openqa.selenium.By
   import org.openqa.selenium.chrome.ChromeDriver
 
   fun main() {
@@ -397,5 +413,5 @@
           driver.quit()
       }
   }
-  

Development Partners

Selenium Level Sponsors

Support the Selenium Project

Learn more or view the full list of sponsors.

Development Partners

Selenium Level Sponsors

Support the Selenium Project

Learn more or view the full list of sponsors.

Deploys by Netlify
© 2024 Software Freedom Conservancy All Rights Reserved

About Selenium

\ No newline at end of file diff --git a/documentation/webdriver/getting_started/_print/index.html b/documentation/webdriver/getting_started/_print/index.html index 0f7cc1f7b33e..c878c133952b 100644 --- a/documentation/webdriver/getting_started/_print/index.html +++ b/documentation/webdriver/getting_started/_print/index.html @@ -49,13 +49,13 @@ testImplementation 'org.junit.jupiter:junit-jupiter-engine:5.11.0'

The minimum supported Python version for each Selenium version can be found in Supported Python Versions on PyPi

There are a couple different ways to install Selenium.

Pip

pip install selenium
-

Download

Alternatively you can download the PyPI source archive +


Download

Alternatively you can download the PyPI source archive (selenium-x.x.x.tar.gz) and install it using setup.py:

python setup.py install
-

Require in project

To use it in a project, add it to the requirements.txt file:

selenium==4.23.1

Require in project

To use it in a project, add it to the requirements.txt file:

selenium==4.23.1

A list of all supported frameworks for each version of Selenium is available on Nuget

There are a few options for installing Selenium.

Packet Manager

Install-Package Selenium.WebDriver
-

.NET CLI

dotnet add package Selenium.WebDriver
-

CSProj

in the project’s csproj file, specify the dependency as a PackageReference in ItemGroup:

      <PackageReference Include="Selenium.WebDriver" Version="4.23.0" />

.NET CLI

dotnet add package Selenium.WebDriver
+

CSProj

in the project’s csproj file, specify the dependency as a PackageReference in ItemGroup:

      <PackageReference Include="Selenium.WebDriver" Version="4.23.0" />

Additional considerations

Further items of note for using Visual Studio Code (vscode) and C#

Install the compatible .NET SDK as per the section above. Also install the vscode extensions (Ctrl-Shift-X) for C# and NuGet. Follow the instruction here @@ -74,10 +74,10 @@ Press Enter and select the version. Now you can use the examples in the documentation related to C# with vscode.

You can see the minimum required version of Ruby for any given Selenium version on rubygems.org

Selenium can be installed two different ways.

Install manually

gem install selenium-webdriver
-

Add to project’s gemfile

gem 'selenium-devtools', '= 0.127.0'

Add to project’s gemfile

gem 'selenium-devtools', '= 0.127.0'

You can find the minimum required version of Node for any given version of Selenium in the Node Support Policy section on npmjs

Selenium is typically installed using npm.

Install locally

npm install selenium-webdriver
-

Add to project

In your project’s package.json, add requirement to dependencies:

        "mocha": "10.7.3"

Add to project

In your project’s package.json, add requirement to dependencies:

        "mocha": "10.7.3"
Use the Java bindings for Kotlin.

Next Step

Create your first Selenium script

2 - Write your first Selenium script

Step-by-step instructions for constructing a Selenium script

Once you have Selenium installed, you’re ready to write Selenium code.

Eight Basic Components

Everything Selenium does is send the browser commands to do something or send requests for information. Most of what you’ll do with Selenium is a combination of these basic commands

Click on the link to “View full example on GitHub” to see the code in context.

1. Start the session

For more details on starting a session read our documentation on driver sessions

		String title = driver.getTitle();
 		assertEquals("Web form", title);
    title = driver.title
-    assert title == "Web form"
            var title = driver.Title;
             Assert.AreEqual("Web form", title);
    title = @driver.title
@@ -269,9 +269,9 @@
 View full example on GitHub

Set Up

def setup():
     driver = webdriver.Chrome()
     driver.get("https://www.selenium.dev/selenium/web/web-form.html")
-    return driver

Tear Down

def teardown(driver):
-    driver.quit()

Set Up

  before do
     @driver = Selenium::WebDriver.for :chrome
   end
@@ -355,9 +355,7 @@ def test_eight_components(): - driver = webdriver.Chrome() - - driver.get("https://www.selenium.dev/selenium/web/web-form.html") + driver = setup() title = driver.title assert title == "Web form" @@ -374,7 +372,7 @@ value = message.text assert value == "Received!" - driver.quit() + teardown(driver) def setup(): driver = webdriver.Chrome() diff --git a/documentation/webdriver/getting_started/install_library/index.html b/documentation/webdriver/getting_started/install_library/index.html index 5651ccdf19ea..403bd0dc40c7 100644 --- a/documentation/webdriver/getting_started/install_library/index.html +++ b/documentation/webdriver/getting_started/install_library/index.html @@ -1,7 +1,7 @@ Install a Selenium library | Selenium

A list of all supported frameworks for each version of Selenium is available on Nuget

There are a few options for installing Selenium.

Packet Manager

Install-Package Selenium.WebDriver
-

.NET CLI

dotnet add package Selenium.WebDriver
-

CSProj

in the project’s csproj file, specify the dependency as a PackageReference in ItemGroup:

      <PackageReference Include="Selenium.WebDriver" Version="4.23.0" />

.NET CLI

dotnet add package Selenium.WebDriver
+

CSProj

in the project’s csproj file, specify the dependency as a PackageReference in ItemGroup:

      <PackageReference Include="Selenium.WebDriver" Version="4.23.0" />

Additional considerations

Further items of note for using Visual Studio Code (vscode) and C#

Install the compatible .NET SDK as per the section above. Also install the vscode extensions (Ctrl-Shift-X) for C# and NuGet. Follow the instruction here @@ -58,9 +58,9 @@ Press Enter and select the version. Now you can use the examples in the documentation related to C# with vscode.

You can see the minimum required version of Ruby for any given Selenium version on rubygems.org

Selenium can be installed two different ways.

Install manually

gem install selenium-webdriver
-

Add to project’s gemfile

gem 'selenium-devtools', '= 0.127.0'

Add to project’s gemfile

gem 'selenium-devtools', '= 0.127.0'

You can find the minimum required version of Node for any given version of Selenium in the Node Support Policy section on npmjs

Selenium is typically installed using npm.

Install locally

npm install selenium-webdriver
-

Add to project

In your project’s package.json, add requirement to dependencies:

        "mocha": "10.7.3"
Use the Java bindings for Kotlin.

Next Step

Create your first Selenium script

Development Partners

Selenium Level Sponsors

Use the Java bindings for Kotlin.

Next Step

Create your first Selenium script

Last modified August 26, 2024: Added breakpoints b/w coding examples in Installing Selenium (#1892) (3688b1e10e6)

Development Partners

Selenium Level Sponsors

Support the Selenium Project

Learn more or view the full list of sponsors.

\ No newline at end of file diff --git a/documentation/webdriver/getting_started/using_selenium/index.html b/documentation/webdriver/getting_started/using_selenium/index.html index 99e1acd36efb..f3f2065eb4d1 100644 --- a/documentation/webdriver/getting_started/using_selenium/index.html +++ b/documentation/webdriver/getting_started/using_selenium/index.html @@ -1,7 +1,7 @@ Organizing and Executing Selenium Code | Selenium

Web要素の検索

提供されたロケーターの値に基づいて要素を検索します。

Seleniumを使用する最も基本的な側面の1つは、操作する要素の参照を取得することです。 + セクション全体を印刷



Web要素の検索

提供されたロケーターの値に基づいて要素を検索します。

Seleniumを使用する最も基本的な側面の1つは、操作する要素の参照を取得することです。 Seleniumは、要素を一意に識別するための多数の組み込みロケーター戦略を提供します。 非常に高度なシナリオでロケーターを使用する方法はたくさんあります。 このドキュメントの目的のために、このHTMLスニペットについて考えてみましょう。

<ol id="vegetables">
@@ -66,49 +66,65 @@
 val fruit = fruits.findElement(By.className("tomatoes"))
   

Java and C#
WebDriverWebElement 、および ShadowRoot クラスはすべて、 ロールベースのインターフェイス と見なされる SearchContext インターフェイスを実装します。 ロールベースのインターフェイスを使用すると、特定のドライバーの実装が特定の機能をサポートしているかどうかを判断できます。 -これらのインターフェースは明確に定義されており、責任の役割を1つだけ持つように努めています。

最適化されたロケーター

ネストされたルックアップは、ブラウザに2つの別々のコマンドを発行する必要があるため、最も効果的なロケーション戦略ではない可能性があります。

パフォーマンスをわずかに向上させるために、CSSまたはXPathのいずれかを使用して、単一のコマンドでこの要素を見つけることができます。 -推奨されるテストプラクティスの章で、ロケーター戦略の提案を参照してください。

この例では、CSSセレクターを使用します。

WebElement fruit = driver.findElement(By.cssSelector("#fruits .tomatoes"));
-  
fruit = driver.find_element(By.CSS_SELECTOR,"#fruits .tomatoes")
-  
var fruit = driver.FindElement(By.CssSelector("#fruits .tomatoes"));
-  
      fruit = driver.find_element(css: '#fruits .tomatoes')
const fruit = await driver.findElement(By.css('#fruits .tomatoes'));
-  
-
val fruit = driver.findElement(By.cssSelector("#fruits .tomatoes"))
-  

一致するすべての要素

最初の要素だけでなく、ロケーターに一致するすべての要素への参照を取得する必要があるユースケースがいくつかあります。 -複数の要素の検索メソッドは、要素参照のコレクションを返します。 -一致するものがない場合は、空のリストが返されます。 -この場合、すべてのfruitsとvegetableのリストアイテムへの参照がコレクションに返されます。

Evaluating the Shadow DOM

The Shadow DOM is an encapsulated DOM tree hidden inside an element. +With the release of v96 in Chromium Browsers, Selenium can now allow you to access this tree +with easy-to-use shadow root methods. NOTE: These methods require Selenium 4.0 or greater.

Move Code

WebElement shadowHost = driver.findElement(By.cssSelector("#shadow_host"));
+SearchContext shadowRoot = shadowHost.getShadowRoot();
+WebElement shadowContent = shadowRoot.findElement(By.cssSelector("#shadow_content"));
shadow_host = driver.find_element(By.CSS_SELECTOR, '#shadow_host')
+shadow_root = shadow_host.shadow_root
+shadow_content = shadow_root.find_element(By.CSS_SELECTOR, '#shadow_content')
var shadowHost = _driver.FindElement(By.CssSelector("#shadow_host"));
+var shadowRoot = shadowHost.GetShadowRoot();
+var shadowContent = shadowRoot.FindElement(By.CssSelector("#shadow_content"));
shadow_host = @driver.find_element(css: '#shadow_host') +shadow_root = shadow_host.shadow_root +shadow_content = shadow_root.find_element(css: '#shadow_content')

最適化されたロケーター

ネストされたルックアップは、ブラウザに2つの別々のコマンドを発行する必要があるため、最も効果的なロケーション戦略ではない可能性があります。

パフォーマンスをわずかに向上させるために、CSSまたはXPathのいずれかを使用して、単一のコマンドでこの要素を見つけることができます。 +推奨されるテストプラクティスの章で、ロケーター戦略の提案を参照してください。

この例では、CSSセレクターを使用します。

List<WebElement> plants = driver.findElements(By.tagName("li"));
-  
plants = driver.find_elements(By.TAG_NAME, "li")
-  
IReadOnlyList<IWebElement> plants = driver.FindElements(By.TagName("li"));
-  
      plants = driver.find_elements(tag_name: 'li')
const plants = await driver.findElements(By.tagName('li'));
+Kotlin
WebElement fruit = driver.findElement(By.cssSelector("#fruits .tomatoes"));
+  
fruit = driver.find_element(By.CSS_SELECTOR,"#fruits .tomatoes")
+  
var fruit = driver.FindElement(By.CssSelector("#fruits .tomatoes"));
+  
      fruit = driver.find_element(css: '#fruits .tomatoes')
const fruit = await driver.findElement(By.css('#fruits .tomatoes'));
   
-
val plants: List<WebElement> = driver.findElements(By.tagName("li"))
-  

要素の取得

多くの場合、要素のコレクションを取得しますが、特定の要素を操作したいので、コレクションを繰り返し処理して、 -必要な要素を特定する必要があります。

val fruit = driver.findElement(By.cssSelector("#fruits .tomatoes"))
+  

一致するすべての要素

最初の要素だけでなく、ロケーターに一致するすべての要素への参照を取得する必要があるユースケースがいくつかあります。 +複数の要素の検索メソッドは、要素参照のコレクションを返します。 +一致するものがない場合は、空のリストが返されます。 +この場合、すべてのfruitsとvegetableのリストアイテムへの参照がコレクションに返されます。

List<WebElement> elements = driver.findElements(By.tagName("li"));
+Kotlin
List<WebElement> plants = driver.findElements(By.tagName("li"));
+  
plants = driver.find_elements(By.TAG_NAME, "li")
+  
IReadOnlyList<IWebElement> plants = driver.FindElements(By.TagName("li"));
+  
      plants = driver.find_elements(tag_name: 'li')
const plants = await driver.findElements(By.tagName('li'));
+  
+
val plants: List<WebElement> = driver.findElements(By.tagName("li"))
+  

要素の取得

多くの場合、要素のコレクションを取得しますが、特定の要素を操作したいので、コレクションを繰り返し処理して、 +必要な要素を特定する必要があります。

List<WebElement> elements = driver.findElements(By.tagName("li"));
 
 for (WebElement element : elements) {
     System.out.println("Paragraph text:" + element.getText());
 }
-  
from selenium import webdriver
+  
from selenium import webdriver
 from selenium.webdriver.common.by import By
 
 driver = webdriver.Firefox()
@@ -121,7 +137,7 @@
 
 for e in elements:
     print(e.text)
-  
using OpenQA.Selenium;
+  
using OpenQA.Selenium;
 using OpenQA.Selenium.Firefox;
 using System.Collections.Generic;
 
@@ -145,9 +161,9 @@
   }
  }
 }
-  
      elements = driver.find_elements(:tag_name,'p')
+  
      elements = driver.find_elements(:tag_name,'p')
          elements.each { |e| puts e.text }
const {Builder, By} = require('selenium-webdriver');
+View full example on GitHub
const {Builder, By} = require('selenium-webdriver');
 (async function example() {
     let driver = await new Builder().forBrowser('firefox').build();
     try {
@@ -165,7 +181,7 @@
     }
 })();
   
-
import org.openqa.selenium.By
+
import org.openqa.selenium.By
 import org.openqa.selenium.firefox.FirefoxDriver
 
 fun main() {
@@ -182,13 +198,13 @@
     }
 }
   

要素から要素を検索

これは、親要素のコンテキスト内で一致する子のWebElementのリストを見つけるために利用されます。 -これを実現するために、親WebElementは’findElements’と連鎖して子要素にアクセスします。

  import org.openqa.selenium.By;
+これを実現するために、親WebElementは’findElements’と連鎖して子要素にアクセスします。

  import org.openqa.selenium.By;
   import org.openqa.selenium.WebDriver;
   import org.openqa.selenium.WebElement;
   import org.openqa.selenium.chrome.ChromeDriver;
@@ -213,7 +229,7 @@
           }
       }
   }
-  
from selenium import webdriver
+  
from selenium import webdriver
 from selenium.webdriver.common.by import By
 
 driver = webdriver.Chrome()
@@ -238,7 +254,7 @@
 elements  = driver.find_elements(By.XPATH, './/li')
 for e in elements:
     print(e.text)
-  
using OpenQA.Selenium;
+  
using OpenQA.Selenium;
 using OpenQA.Selenium.Chrome;
 using System.Collections.Generic;
 
@@ -263,10 +279,10 @@
   }
  }
 }
-  
      element = driver.find_element(:tag_name,'div')
+  
      element = driver.find_element(:tag_name,'div')
          elements = element.find_elements(:tag_name,'p')
          elements.each { |e| puts e.text }
  const {Builder, By} = require('selenium-webdriver');
+View full example on GitHub
  const {Builder, By} = require('selenium-webdriver');
 
   (async function example() {
       let driver = new Builder()
@@ -285,7 +301,7 @@
       }
   })();
   
-
  import org.openqa.selenium.By
+
  import org.openqa.selenium.By
   import org.openqa.selenium.chrome.ChromeDriver
 
   fun main() {
@@ -305,13 +321,13 @@
           driver.quit()
       }
   }
-  

アクティブな要素を取得する

これは、現在のブラウジングコンテキストでフォーカスを持っているDOM要素を追跡(または)検索するために使用されます。

  import org.openqa.selenium.*;
+  

アクティブな要素を取得する

これは、現在のブラウジングコンテキストでフォーカスを持っているDOM要素を追跡(または)検索するために使用されます。

  import org.openqa.selenium.*;
   import org.openqa.selenium.chrome.ChromeDriver;
 
   public class activeElementTest {
@@ -329,7 +345,7 @@
       }
     }
   }
-  
  from selenium import webdriver
+  
  from selenium import webdriver
   from selenium.webdriver.common.by import By
 
   driver = webdriver.Chrome()
@@ -339,7 +355,7 @@
     # Get attribute of current active element
   attr = driver.switch_to.active_element.get_attribute("title")
   print(attr)
-  
    using OpenQA.Selenium;
+  
    using OpenQA.Selenium;
     using OpenQA.Selenium.Chrome;
 
     namespace ActiveElement {
@@ -360,9 +376,9 @@
       }
      }
     }
-  
      driver.find_element(css: '[name="q"]').send_keys('webElement')
+  
      driver.find_element(css: '[name="q"]').send_keys('webElement')
         attr = driver.switch_to.active_element.attribute('title')
  const {Builder, By} = require('selenium-webdriver');
+View full example on GitHub
  const {Builder, By} = require('selenium-webdriver');
 
   (async function example() {
       let driver = await new Builder().forBrowser('chrome').build();
@@ -374,7 +390,7 @@
       console.log(`${attr}`)
   })();
   
-
  import org.openqa.selenium.By
+
  import org.openqa.selenium.By
   import org.openqa.selenium.chrome.ChromeDriver
 
   fun main() {
@@ -390,5 +406,5 @@
           driver.quit()
       }
   }
-  

Development Partners

Selenium Level Sponsors

Support the Selenium Project

Learn more or view the full list of sponsors.

最終更新 August 26, 2024: added shadow dom documentation to finders in all translations #1070 (#1887)[deploy site] (bb164c33902)

Development Partners

Selenium Level Sponsors

Support the Selenium Project

Learn more or view the full list of sponsors.

\ No newline at end of file diff --git a/ja/documentation/webdriver/getting_started/_print/index.html b/ja/documentation/webdriver/getting_started/_print/index.html index d31aad844176..4d1c7048e61c 100644 --- a/ja/documentation/webdriver/getting_started/_print/index.html +++ b/ja/documentation/webdriver/getting_started/_print/index.html @@ -38,13 +38,13 @@ testImplementation 'org.junit.jupiter:junit-jupiter-engine:5.11.0'

The minimum supported Python version for each Selenium version can be found in Supported Python Versions on PyPi

There are a couple different ways to install Selenium.

Pip

pip install selenium
-

Download

Alternatively you can download the PyPI source archive +


Download

Alternatively you can download the PyPI source archive (selenium-x.x.x.tar.gz) and install it using setup.py:

python setup.py install
-

Require in project

To use it in a project, add it to the requirements.txt file:

selenium==4.23.1
+

Require in project

To use it in a project, add it to the requirements.txt file:

selenium==4.23.1
View full example on GitHub

A list of all supported frameworks for each version of Selenium is available on Nuget

There are a few options for installing Selenium.

Packet Manager

Install-Package Selenium.WebDriver
-

.NET CLI

dotnet add package Selenium.WebDriver
-

CSProj

in the project’s csproj file, specify the dependency as a PackageReference in ItemGroup:

      <PackageReference Include="Selenium.WebDriver" Version="4.23.0" />
+

.NET CLI

dotnet add package Selenium.WebDriver
+

CSProj

in the project’s csproj file, specify the dependency as a PackageReference in ItemGroup:

      <PackageReference Include="Selenium.WebDriver" Version="4.23.0" />
View full example on GitHub

Additional considerations

Further items of note for using Visual Studio Code (vscode) and C#

Install the compatible .NET SDK as per the section above. Also install the vscode extensions (Ctrl-Shift-X) for C# and NuGet. Follow the instruction here @@ -63,10 +63,10 @@ Press Enter and select the version. Now you can use the examples in the documentation related to C# with vscode.

You can see the minimum required version of Ruby for any given Selenium version on rubygems.org

Selenium can be installed two different ways.

Install manually

gem install selenium-webdriver
-

Add to project’s gemfile

gem 'selenium-devtools', '= 0.127.0'
+

Add to project’s gemfile

gem 'selenium-devtools', '= 0.127.0'
View full example on GitHub

You can find the minimum required version of Node for any given version of Selenium in the Node Support Policy section on npmjs

Selenium is typically installed using npm.

Install locally

npm install selenium-webdriver
-

Add to project

In your project’s package.json, add requirement to dependencies:

        "mocha": "10.7.3"
+

Add to project

In your project’s package.json, add requirement to dependencies:

        "mocha": "10.7.3"
View full example on GitHub
Use the Java bindings for Kotlin.

Next Step

Create your first Selenium script

2 - 最初のSeleniumスクリプトを書く

Seleniumスクリプトを作成するための段階的な説明

Seleniumをインストールし、 すると、Seleniumコードを書く準備が整います。

Eight Basic Components

Seleniumが行うことはすべて、ブラウザコマンドを送信して、何かを実行したり、情報の要求を送信したりすることです。 Seleniumで行うことのほとんどは、次の基本的なコマンドの組み合わせです。

Click on the link to “View full example on GitHub” to see the code in context.

1. ドライバーインスタンスでセッションを開始します

For more details on starting a session read our documentation on driver sessions

driver.get('https://www.selenium.dev/selenium/web/web-form.html')
View full example on GitHub
    await driver.get('https://www.selenium.dev/selenium/web/web-form.html');
View full example on GitHub
        driver.get("https://www.selenium.dev/selenium/web/web-form.html")
-View full example on GitHub

3. ブラウザに関する情報をリクエストします

There are a bunch of types of information about the browser you +View full example on GitHub

3. ブラウザに関する情報をリクエストします

There are a bunch of types of information about the browser you can request, including window handles, browser size / position, cookies, alerts, etc.

		String title = driver.getTitle();
 		assertEquals("Web form", title);
    title = driver.title
-    assert title == "Web form"
            var title = driver.Title;
             Assert.AreEqual("Web form", title);
    title = @driver.title
@@ -257,9 +257,9 @@
 View full example on GitHub

Set Up

def setup():
     driver = webdriver.Chrome()
     driver.get("https://www.selenium.dev/selenium/web/web-form.html")
-    return driver

Tear Down

def teardown(driver):
-    driver.quit()

Add Example

Set Up

  before do
     @driver = Selenium::WebDriver.for :chrome
   end

最初のSeleniumスクリプトを書く

Seleniumスクリプトを作成するための段階的な説明

Seleniumをインストールし、 + セクション全体を印刷



最初のSeleniumスクリプトを書く

Seleniumスクリプトを作成するための段階的な説明

Seleniumをインストールし、 すると、Seleniumコードを書く準備が整います。

Eight Basic Components

Seleniumが行うことはすべて、ブラウザコマンドを送信して、何かを実行したり、情報の要求を送信したりすることです。 Seleniumで行うことのほとんどは、次の基本的なコマンドの組み合わせです。

Click on the link to “View full example on GitHub” to see the code in context.

1. ドライバーインスタンスでセッションを開始します

For more details on starting a session read our documentation on driver sessions

driver.get('https://www.selenium.dev/selenium/web/web-form.html')
    await driver.get('https://www.selenium.dev/selenium/web/web-form.html');
        driver.get("https://www.selenium.dev/selenium/web/web-form.html")

3. ブラウザに関する情報をリクエストします

There are a bunch of types of information about the browser you +View full example on GitHub

3. ブラウザに関する情報をリクエストします

There are a bunch of types of information about the browser you can request, including window handles, browser size / position, cookies, alerts, etc.

WebElement fruit = driver.findElement(By.cssSelector("#fruits .tomatoes"));
+  
fruit = driver.find_element(By.CSS_SELECTOR,"#fruits .tomatoes")
+  
var fruit = driver.FindElement(By.CssSelector("#fruits .tomatoes"));
+  
      fruit = driver.find_element(css: '#fruits .tomatoes')
const fruit = await driver.findElement(By.css('#fruits .tomatoes'));
   
-
val plants: List<WebElement> = driver.findElements(By.tagName("li"))
-  

Obter Elemento

Muitas vezes você obterá uma coleção de elementos, mas quer trabalhar apenas com um elemento específico, o que significa que você -precisa iterar sobre a coleção e identificar o que você deseja.

List<WebElement> elements = driver.findElements(By.tagName("li"));
+Kotlin
List<WebElement> plants = driver.findElements(By.tagName("li"));
+  
plants = driver.find_elements(By.TAG_NAME, "li")
+  
IReadOnlyList<IWebElement> plants = driver.FindElements(By.TagName("li"));
+  
      plants = driver.find_elements(tag_name: 'li')
const plants = await driver.findElements(By.tagName('li'));
+  
+
val plants: List<WebElement> = driver.findElements(By.tagName("li"))
+  

Obter Elemento

Muitas vezes você obterá uma coleção de elementos, mas quer trabalhar apenas com um elemento específico, o que significa que você +precisa iterar sobre a coleção e identificar o que você deseja.

List<WebElement> elements = driver.findElements(By.tagName("li"));
 
 for (WebElement element : elements) {
     System.out.println("Paragraph text:" + element.getText());
 }
-  
from selenium import webdriver
+  
from selenium import webdriver
 from selenium.webdriver.common.by import By
 
 driver = webdriver.Firefox()
@@ -2633,7 +2647,7 @@
 
 for e in elements:
     print(e.text)
-  
using OpenQA.Selenium;
+  
using OpenQA.Selenium;
 using OpenQA.Selenium.Firefox;
 using System.Collections.Generic;
 
@@ -2657,9 +2671,9 @@
   }
  }
 }
-  
      elements = driver.find_elements(:tag_name,'p')
+  
      elements = driver.find_elements(:tag_name,'p')
          elements.each { |e| puts e.text }
const {Builder, By} = require('selenium-webdriver');
+View full example on GitHub
const {Builder, By} = require('selenium-webdriver');
 (async function example() {
     let driver = await new Builder().forBrowser('firefox').build();
     try {
@@ -2677,7 +2691,7 @@
     }
 })();
   
-
import org.openqa.selenium.By
+
import org.openqa.selenium.By
 import org.openqa.selenium.firefox.FirefoxDriver
 
 fun main() {
@@ -2694,13 +2708,13 @@
     }
 }
   

Localizar Elementos em um Elemento

Ele é usado para localizar a lista de WebElements filhos correspondentes dentro do contexto do elemento pai. -Para realizar isso, o WebElement pai é encadeado com o ‘findElements’ para acessar seus elementos filhos.

  import org.openqa.selenium.By;
+Para realizar isso, o WebElement pai é encadeado com o ‘findElements’ para acessar seus elementos filhos.

  import org.openqa.selenium.By;
   import org.openqa.selenium.WebDriver;
   import org.openqa.selenium.WebElement;
   import org.openqa.selenium.chrome.ChromeDriver;
@@ -2725,7 +2739,7 @@
           }
       }
   }
-  
##get elements from parent element using TAG_NAME
+  
##get elements from parent element using TAG_NAME
 
     # Obtém o elemento com o nome da tag 'div'
 element = driver.find_element(By.TAG_NAME, 'div')
@@ -2745,7 +2759,7 @@
 elements  = driver.find_elements(By.XPATH, './/li')
 for e in elements:
     print(e.text)
-  
using OpenQA.Selenium;
+  
using OpenQA.Selenium;
 using OpenQA.Selenium.Chrome;
 using System.Collections.Generic;
 
@@ -2770,10 +2784,10 @@
   }
  }
 }
-  
      element = driver.find_element(:tag_name,'div')
+  
      element = driver.find_element(:tag_name,'div')
          elements = element.find_elements(:tag_name,'p')
          elements.each { |e| puts e.text }
  const {Builder, By} = require('selenium-webdriver');
+View full example on GitHub
  const {Builder, By} = require('selenium-webdriver');
 
   (async function example() {
       let driver = new Builder()
@@ -2792,7 +2806,7 @@
       }
   })();
   
-
  import org.openqa.selenium.By
+
  import org.openqa.selenium.By
   import org.openqa.selenium.chrome.ChromeDriver
 
   fun main() {
@@ -2812,13 +2826,13 @@
           driver.quit()
       }
   }
-  

Obter elemento ativo

Ele é usado para rastrear (ou) encontrar um elemento DOM que tem o foco no contexto de navegação atual.

  import org.openqa.selenium.*;
+  

Obter elemento ativo

Ele é usado para rastrear (ou) encontrar um elemento DOM que tem o foco no contexto de navegação atual.

  import org.openqa.selenium.*;
   import org.openqa.selenium.chrome.ChromeDriver;
 
   public class activeElementTest {
@@ -2836,7 +2850,7 @@
       }
     }
   }
-  
  from selenium import webdriver
+  
  from selenium import webdriver
   from selenium.webdriver.common.by import By
 
   driver = webdriver.Chrome()
@@ -2846,7 +2860,7 @@
     # Obter atributo do elemento atualmente ativo
   attr = driver.switch_to.active_element.get_attribute("title")
   print(attr)
-  
    using OpenQA.Selenium;
+  
    using OpenQA.Selenium;
     using OpenQA.Selenium.Chrome;
 
     namespace ActiveElement {
@@ -2867,9 +2881,9 @@
       }
      }
     }
-  
      driver.find_element(css: '[name="q"]').send_keys('webElement')
+  
      driver.find_element(css: '[name="q"]').send_keys('webElement')
         attr = driver.switch_to.active_element.attribute('title')
  const {Builder, By} = require('selenium-webdriver');
+View full example on GitHub
  const {Builder, By} = require('selenium-webdriver');
 
   (async function example() {
       let driver = await new Builder().forBrowser('chrome').build();
@@ -2881,7 +2895,7 @@
       console.log(`${attr}`)
   })();
   
-
  import org.openqa.selenium.By
+
  import org.openqa.selenium.By
   import org.openqa.selenium.chrome.ChromeDriver
 
   fun main() {
@@ -13471,7 +13485,7 @@
 das informações contidas neste livro. Nenhuma responsabilidade de patente é assumida com
 relação ao uso das informações aqui contidas.

Atribuições

Agradecimentos:

Selenium Main Repository

-5320 commits
+5321 commits
3352 commits
@@ -13999,7 +14013,9 @@ 17 commits
-15 commits
+15 commits
+ +13 commits
@@ -14009,8 +14025,6 @@ 10 commits
-8 commits
- 8 commits
7 commits
diff --git a/pt-br/documentation/about/_print/index.html b/pt-br/documentation/about/_print/index.html index e00a8bbbb6a0..53940c3dccfe 100644 --- a/pt-br/documentation/about/_print/index.html +++ b/pt-br/documentation/about/_print/index.html @@ -35,7 +35,7 @@ das informações contidas neste livro. Nenhuma responsabilidade de patente é assumida com relação ao uso das informações aqui contidas.

Atribuições

Agradecimentos:

Selenium Main Repository

-5320 commits
+5321 commits
3352 commits
@@ -563,7 +563,9 @@ 17 commits
-15 commits
+15 commits
+ +13 commits
@@ -573,8 +575,6 @@ 10 commits
-8 commits
- 8 commits
7 commits
diff --git a/pt-br/documentation/about/copyright/index.html b/pt-br/documentation/about/copyright/index.html index 44308f6ae4af..210e1abbf23f 100644 --- a/pt-br/documentation/about/copyright/index.html +++ b/pt-br/documentation/about/copyright/index.html @@ -22,7 +22,7 @@ das informações contidas neste livro. Nenhuma responsabilidade de patente é assumida com relação ao uso das informações aqui contidas.

Atribuições

Agradecimentos:

Selenium Main Repository

-5320 commits
+5321 commits
3352 commits
@@ -550,7 +550,9 @@ 17 commits
-15 commits
+15 commits
+ +13 commits
@@ -560,8 +562,6 @@ 10 commits
-8 commits
- 8 commits
7 commits
diff --git a/pt-br/documentation/webdriver/_print/index.html b/pt-br/documentation/webdriver/_print/index.html index 54856e292818..8929d046741a 100644 --- a/pt-br/documentation/webdriver/_print/index.html +++ b/pt-br/documentation/webdriver/_print/index.html @@ -48,13 +48,13 @@ testImplementation 'org.junit.jupiter:junit-jupiter-engine:5.11.0'

A mínima versão suportada do Python para cada versão do Selenium pode ser encontrada em Supported Python Versions no PyPi

Existe muitas formas diferentes de instalar Selenium.

Pip

pip install selenium
-

Download

Como uma alternativa você pode baixar o código fonte PyPI +


Download

Como uma alternativa você pode baixar o código fonte PyPI (selenium-x.x.x.tar.gz) e instalar usando setup.py:

python setup.py install
-

Exigir em um projeto

Para usar em um projeto, adicione no arquivo requirements.txt.

selenium==4.23.1

Exigir em um projeto

Para usar em um projeto, adicione no arquivo requirements.txt.

selenium==4.23.1

Uma lista com todos os frameworks suportados para cada versão do Selenium pode ser encontrada em Nuget

Existe algumas opções para instalar o Selenium.

Packet Manager

Install-Package Selenium.WebDriver
-

.NET CLI

dotnet add package Selenium.WebDriver
-

CSProj

No arquivo csproj do seu projeto, especifique a dependência como PackageReference no ItemGroup:

      <PackageReference Include="Selenium.WebDriver" Version="4.23.0" />

.NET CLI

dotnet add package Selenium.WebDriver
+

CSProj

No arquivo csproj do seu projeto, especifique a dependência como PackageReference no ItemGroup:

      <PackageReference Include="Selenium.WebDriver" Version="4.23.0" />

Considerações adicionais

Outras observações para usar o Visual Studio Code (vscode) e C#

Instale a versão compatível do .NET SDK conforme a seção acima. Instale também as extensões do vscode (Ctrl-Shift-X) para C# e NuGet. Siga as instruções aqui para criar e rodar o seu projeto de “Hello World” no console usando C#.

Você também pode criar um projeto inicial do NUnit usando a linha de comando dotnet new NUnit. @@ -72,10 +72,10 @@ Aperte Enter e selecione a versão. Agora você pode usar os exemplos da documentação relacionados ao C# com o vscode.

Você pode ver a minima versão suportada do Ruby para cada versão do Selenium em rubygems.org

O Selenium pode ser instalado de duas formas diferentes.

Instalação manual

gem install selenium-webdriver
-

Adicione para o gemfile do projeto

gem 'selenium-devtools', '= 0.127.0'

Adicione para o gemfile do projeto

gem 'selenium-devtools', '= 0.127.0'

Você pode encontrar a mínima versão suportada do Node para cada versão do Selenium na seção Node Support Policy no site npmjs

Selenium é normalmente instalado usando npm.

Instalação local

npm install selenium-webdriver
-

Adicione ao seu projeto

No package.json do seu projeto, adicione os requisitos em dependencies:

        "mocha": "10.7.3"

Adicione ao seu projeto

No package.json do seu projeto, adicione os requisitos em dependencies:

        "mocha": "10.7.3"
Use as ligações Java para Kotlin.

Próximo passo

Programando o seu primeiro script Selenium

1.2 - Programe o seu primeiro script Selenium

Instruções passo a passo para programar um script Selenium

Assim que você tiver o Selenium instalado, você estará pronto para programar códigos Selenium.

Oito Componentes Básicos

Tudo que o Selenium faz é enviar comandos ao navegador de internet para fazer algo ou solicitar informações dele. A maior parte do que você irá fazer com o Selenium é uma combinação desses comandos básicos.

Click on the link to “View full example on GitHub” to see the code in context.

1. Iniciando uma sessão

Para ter mais detalhes sobre como iniciar uma sessão, leia nossa documentação em driver sessions

		String title = driver.getTitle();
 		assertEquals("Web form", title);
    title = driver.title
-    assert title == "Web form"
            var title = driver.Title;
             Assert.AreEqual("Web form", title);
    title = @driver.title
@@ -268,9 +268,9 @@
 View full example on GitHub

Set Up

def setup():
     driver = webdriver.Chrome()
     driver.get("https://www.selenium.dev/selenium/web/web-form.html")
-    return driver

Tear Down

def teardown(driver):
-    driver.quit()

Java e C#
As classes WebDriver, WebElement e ShadowRoot todas implementam o SearchContext interface, que é considerada uma role-based interface(interface baseada em função). As interfaces baseadas em função permitem determinar se uma determinada implementação de driver suporta um recurso específico. Essas interfaces são claramente definidas e tentam -aderir a ter apenas um único papel de responsabilidade.

Localizador otimizado

Uma pesquisa aninhada pode não ser a estratégia de localização mais eficaz, pois requer dois +aderir a ter apenas um único papel de responsabilidade.

Evaluating the Shadow DOM

The Shadow DOM is an encapsulated DOM tree hidden inside an element. +With the release of v96 in Chromium Browsers, Selenium can now allow you to access this tree +with easy-to-use shadow root methods. NOTE: These methods require Selenium 4.0 or greater.

Move Code

WebElement shadowHost = driver.findElement(By.cssSelector("#shadow_host"));
+SearchContext shadowRoot = shadowHost.getShadowRoot();
+WebElement shadowContent = shadowRoot.findElement(By.cssSelector("#shadow_content"));
shadow_host = driver.find_element(By.CSS_SELECTOR, '#shadow_host')
+shadow_root = shadow_host.shadow_root
+shadow_content = shadow_root.find_element(By.CSS_SELECTOR, '#shadow_content')
var shadowHost = _driver.FindElement(By.CssSelector("#shadow_host"));
+var shadowRoot = shadowHost.GetShadowRoot();
+var shadowContent = shadowRoot.FindElement(By.CssSelector("#shadow_content"));
shadow_host = @driver.find_element(css: '#shadow_host') +shadow_root = shadow_host.shadow_root +shadow_content = shadow_root.find_element(css: '#shadow_content')

Localizador otimizado

Uma pesquisa aninhada pode não ser a estratégia de localização mais eficaz, pois requer dois comandos separados a serem emitidos para o navegador.

Para melhorar um pouco o desempenho, podemos usar CSS ou XPath para encontrar esse elemento com um único comando. Veja as sugestões de estratégia do localizador na nossa sessão de -Práticas de teste incentivadas.

Para esse exemplo, utilizaremos o CSS Selector:

WebElement fruit = driver.findElement(By.cssSelector("#fruits .tomatoes"));
-  
fruit = driver.find_element(By.CSS_SELECTOR,"#fruits .tomatoes")
-  
var fruit = driver.FindElement(By.CssSelector("#fruits .tomatoes"));
-  
      fruit = driver.find_element(css: '#fruits .tomatoes')
const fruit = await driver.findElement(By.css('#fruits .tomatoes'));
-  
-
val fruit = driver.findElement(By.cssSelector("#fruits .tomatoes"))
-  

Todos os elementos correspondentes

Existem vários casos de uso para a necessidade de obter referências a todos os elementos que correspondem a um localizador, em vez -do que apenas o primeiro. Os métodos plurais find elements retornam uma coleção de referências de elementos. -Se não houver correspondências, uma lista vazia será retornada. Nesse caso, -referências a todos os itens da lista de frutas e vegetais serão devolvidas em uma coleção.

List<WebElement> plants = driver.findElements(By.tagName("li"));
-  
plants = driver.find_elements(By.TAG_NAME, "li")
-  
IReadOnlyList<IWebElement> plants = driver.FindElements(By.TagName("li"));
-  
      plants = driver.find_elements(tag_name: 'li')
const plants = await driver.findElements(By.tagName('li'));
+Kotlin
WebElement fruit = driver.findElement(By.cssSelector("#fruits .tomatoes"));
+  
fruit = driver.find_element(By.CSS_SELECTOR,"#fruits .tomatoes")
+  
var fruit = driver.FindElement(By.CssSelector("#fruits .tomatoes"));
+  
      fruit = driver.find_element(css: '#fruits .tomatoes')
const fruit = await driver.findElement(By.css('#fruits .tomatoes'));
   
-
val plants: List<WebElement> = driver.findElements(By.tagName("li"))
-  

Obter Elemento

Muitas vezes você obterá uma coleção de elementos, mas quer trabalhar apenas com um elemento específico, o que significa que você -precisa iterar sobre a coleção e identificar o que você deseja.

val fruit = driver.findElement(By.cssSelector("#fruits .tomatoes"))
+  

Todos os elementos correspondentes

Existem vários casos de uso para a necessidade de obter referências a todos os elementos que correspondem a um localizador, em vez +do que apenas o primeiro. Os métodos plurais find elements retornam uma coleção de referências de elementos. +Se não houver correspondências, uma lista vazia será retornada. Nesse caso, +referências a todos os itens da lista de frutas e vegetais serão devolvidas em uma coleção.

List<WebElement> elements = driver.findElements(By.tagName("li"));
+Kotlin
List<WebElement> plants = driver.findElements(By.tagName("li"));
+  
plants = driver.find_elements(By.TAG_NAME, "li")
+  
IReadOnlyList<IWebElement> plants = driver.FindElements(By.TagName("li"));
+  
      plants = driver.find_elements(tag_name: 'li')
const plants = await driver.findElements(By.tagName('li'));
+  
+
val plants: List<WebElement> = driver.findElements(By.tagName("li"))
+  

Obter Elemento

Muitas vezes você obterá uma coleção de elementos, mas quer trabalhar apenas com um elemento específico, o que significa que você +precisa iterar sobre a coleção e identificar o que você deseja.

List<WebElement> elements = driver.findElements(By.tagName("li"));
 
 for (WebElement element : elements) {
     System.out.println("Paragraph text:" + element.getText());
 }
-  
from selenium import webdriver
+  
from selenium import webdriver
 from selenium.webdriver.common.by import By
 
 driver = webdriver.Firefox()
@@ -2436,7 +2450,7 @@
 
 for e in elements:
     print(e.text)
-  
using OpenQA.Selenium;
+  
using OpenQA.Selenium;
 using OpenQA.Selenium.Firefox;
 using System.Collections.Generic;
 
@@ -2460,9 +2474,9 @@
   }
  }
 }
-  
      elements = driver.find_elements(:tag_name,'p')
+  
      elements = driver.find_elements(:tag_name,'p')
          elements.each { |e| puts e.text }
const {Builder, By} = require('selenium-webdriver');
+View full example on GitHub
const {Builder, By} = require('selenium-webdriver');
 (async function example() {
     let driver = await new Builder().forBrowser('firefox').build();
     try {
@@ -2480,7 +2494,7 @@
     }
 })();
   
-
import org.openqa.selenium.By
+
import org.openqa.selenium.By
 import org.openqa.selenium.firefox.FirefoxDriver
 
 fun main() {
@@ -2497,13 +2511,13 @@
     }
 }
   

Localizar Elementos em um Elemento

Ele é usado para localizar a lista de WebElements filhos correspondentes dentro do contexto do elemento pai. -Para realizar isso, o WebElement pai é encadeado com o ‘findElements’ para acessar seus elementos filhos.

  import org.openqa.selenium.By;
+Para realizar isso, o WebElement pai é encadeado com o ‘findElements’ para acessar seus elementos filhos.

  import org.openqa.selenium.By;
   import org.openqa.selenium.WebDriver;
   import org.openqa.selenium.WebElement;
   import org.openqa.selenium.chrome.ChromeDriver;
@@ -2528,7 +2542,7 @@
           }
       }
   }
-  
##get elements from parent element using TAG_NAME
+  
##get elements from parent element using TAG_NAME
 
     # Obtém o elemento com o nome da tag 'div'
 element = driver.find_element(By.TAG_NAME, 'div')
@@ -2548,7 +2562,7 @@
 elements  = driver.find_elements(By.XPATH, './/li')
 for e in elements:
     print(e.text)
-  
using OpenQA.Selenium;
+  
using OpenQA.Selenium;
 using OpenQA.Selenium.Chrome;
 using System.Collections.Generic;
 
@@ -2573,10 +2587,10 @@
   }
  }
 }
-  
      element = driver.find_element(:tag_name,'div')
+  
      element = driver.find_element(:tag_name,'div')
          elements = element.find_elements(:tag_name,'p')
          elements.each { |e| puts e.text }
  const {Builder, By} = require('selenium-webdriver');
+View full example on GitHub
  const {Builder, By} = require('selenium-webdriver');
 
   (async function example() {
       let driver = new Builder()
@@ -2595,7 +2609,7 @@
       }
   })();
   
-
  import org.openqa.selenium.By
+
  import org.openqa.selenium.By
   import org.openqa.selenium.chrome.ChromeDriver
 
   fun main() {
@@ -2615,13 +2629,13 @@
           driver.quit()
       }
   }
-  

Obter elemento ativo

Ele é usado para rastrear (ou) encontrar um elemento DOM que tem o foco no contexto de navegação atual.

  import org.openqa.selenium.*;
+  

Obter elemento ativo

Ele é usado para rastrear (ou) encontrar um elemento DOM que tem o foco no contexto de navegação atual.

  import org.openqa.selenium.*;
   import org.openqa.selenium.chrome.ChromeDriver;
 
   public class activeElementTest {
@@ -2639,7 +2653,7 @@
       }
     }
   }
-  
  from selenium import webdriver
+  
  from selenium import webdriver
   from selenium.webdriver.common.by import By
 
   driver = webdriver.Chrome()
@@ -2649,7 +2663,7 @@
     # Obter atributo do elemento atualmente ativo
   attr = driver.switch_to.active_element.get_attribute("title")
   print(attr)
-  
    using OpenQA.Selenium;
+  
    using OpenQA.Selenium;
     using OpenQA.Selenium.Chrome;
 
     namespace ActiveElement {
@@ -2670,9 +2684,9 @@
       }
      }
     }
-  
      driver.find_element(css: '[name="q"]').send_keys('webElement')
+  
      driver.find_element(css: '[name="q"]').send_keys('webElement')
         attr = driver.switch_to.active_element.attribute('title')
  const {Builder, By} = require('selenium-webdriver');
+View full example on GitHub
  const {Builder, By} = require('selenium-webdriver');
 
   (async function example() {
       let driver = await new Builder().forBrowser('chrome').build();
@@ -2684,7 +2698,7 @@
       console.log(`${attr}`)
   })();
   
-
  import org.openqa.selenium.By
+
  import org.openqa.selenium.By
   import org.openqa.selenium.chrome.ChromeDriver
 
   fun main() {
diff --git a/pt-br/documentation/webdriver/elements/_print/index.html b/pt-br/documentation/webdriver/elements/_print/index.html
index 4a3fb07c523f..2b3dbd42591d 100644
--- a/pt-br/documentation/webdriver/elements/_print/index.html
+++ b/pt-br/documentation/webdriver/elements/_print/index.html
@@ -107,51 +107,67 @@
   

Java e C#
As classes WebDriver, WebElement e ShadowRoot todas implementam o SearchContext interface, que é considerada uma role-based interface(interface baseada em função). As interfaces baseadas em função permitem determinar se uma determinada implementação de driver suporta um recurso específico. Essas interfaces são claramente definidas e tentam -aderir a ter apenas um único papel de responsabilidade.

Localizador otimizado

Uma pesquisa aninhada pode não ser a estratégia de localização mais eficaz, pois requer dois +aderir a ter apenas um único papel de responsabilidade.

Evaluating the Shadow DOM

The Shadow DOM is an encapsulated DOM tree hidden inside an element. +With the release of v96 in Chromium Browsers, Selenium can now allow you to access this tree +with easy-to-use shadow root methods. NOTE: These methods require Selenium 4.0 or greater.

Move Code

WebElement shadowHost = driver.findElement(By.cssSelector("#shadow_host"));
+SearchContext shadowRoot = shadowHost.getShadowRoot();
+WebElement shadowContent = shadowRoot.findElement(By.cssSelector("#shadow_content"));
shadow_host = driver.find_element(By.CSS_SELECTOR, '#shadow_host')
+shadow_root = shadow_host.shadow_root
+shadow_content = shadow_root.find_element(By.CSS_SELECTOR, '#shadow_content')
var shadowHost = _driver.FindElement(By.CssSelector("#shadow_host"));
+var shadowRoot = shadowHost.GetShadowRoot();
+var shadowContent = shadowRoot.FindElement(By.CssSelector("#shadow_content"));
shadow_host = @driver.find_element(css: '#shadow_host') +shadow_root = shadow_host.shadow_root +shadow_content = shadow_root.find_element(css: '#shadow_content')

Localizador otimizado

Uma pesquisa aninhada pode não ser a estratégia de localização mais eficaz, pois requer dois comandos separados a serem emitidos para o navegador.

Para melhorar um pouco o desempenho, podemos usar CSS ou XPath para encontrar esse elemento com um único comando. Veja as sugestões de estratégia do localizador na nossa sessão de -Práticas de teste incentivadas.

Para esse exemplo, utilizaremos o CSS Selector:

WebElement fruit = driver.findElement(By.cssSelector("#fruits .tomatoes"));
-  
fruit = driver.find_element(By.CSS_SELECTOR,"#fruits .tomatoes")
-  
var fruit = driver.FindElement(By.CssSelector("#fruits .tomatoes"));
-  
      fruit = driver.find_element(css: '#fruits .tomatoes')
const fruit = await driver.findElement(By.css('#fruits .tomatoes'));
-  
-
val fruit = driver.findElement(By.cssSelector("#fruits .tomatoes"))
-  

Todos os elementos correspondentes

Existem vários casos de uso para a necessidade de obter referências a todos os elementos que correspondem a um localizador, em vez -do que apenas o primeiro. Os métodos plurais find elements retornam uma coleção de referências de elementos. -Se não houver correspondências, uma lista vazia será retornada. Nesse caso, -referências a todos os itens da lista de frutas e vegetais serão devolvidas em uma coleção.

List<WebElement> plants = driver.findElements(By.tagName("li"));
-  
plants = driver.find_elements(By.TAG_NAME, "li")
-  
IReadOnlyList<IWebElement> plants = driver.FindElements(By.TagName("li"));
-  
      plants = driver.find_elements(tag_name: 'li')
const plants = await driver.findElements(By.tagName('li'));
+Kotlin
WebElement fruit = driver.findElement(By.cssSelector("#fruits .tomatoes"));
+  
fruit = driver.find_element(By.CSS_SELECTOR,"#fruits .tomatoes")
+  
var fruit = driver.FindElement(By.CssSelector("#fruits .tomatoes"));
+  
      fruit = driver.find_element(css: '#fruits .tomatoes')
const fruit = await driver.findElement(By.css('#fruits .tomatoes'));
   
-
val plants: List<WebElement> = driver.findElements(By.tagName("li"))
-  

Obter Elemento

Muitas vezes você obterá uma coleção de elementos, mas quer trabalhar apenas com um elemento específico, o que significa que você -precisa iterar sobre a coleção e identificar o que você deseja.

val fruit = driver.findElement(By.cssSelector("#fruits .tomatoes"))
+  

Todos os elementos correspondentes

Existem vários casos de uso para a necessidade de obter referências a todos os elementos que correspondem a um localizador, em vez +do que apenas o primeiro. Os métodos plurais find elements retornam uma coleção de referências de elementos. +Se não houver correspondências, uma lista vazia será retornada. Nesse caso, +referências a todos os itens da lista de frutas e vegetais serão devolvidas em uma coleção.

List<WebElement> elements = driver.findElements(By.tagName("li"));
+Kotlin
List<WebElement> plants = driver.findElements(By.tagName("li"));
+  
plants = driver.find_elements(By.TAG_NAME, "li")
+  
IReadOnlyList<IWebElement> plants = driver.FindElements(By.TagName("li"));
+  
      plants = driver.find_elements(tag_name: 'li')
const plants = await driver.findElements(By.tagName('li'));
+  
+
val plants: List<WebElement> = driver.findElements(By.tagName("li"))
+  

Obter Elemento

Muitas vezes você obterá uma coleção de elementos, mas quer trabalhar apenas com um elemento específico, o que significa que você +precisa iterar sobre a coleção e identificar o que você deseja.

List<WebElement> elements = driver.findElements(By.tagName("li"));
 
 for (WebElement element : elements) {
     System.out.println("Paragraph text:" + element.getText());
 }
-  
from selenium import webdriver
+  
from selenium import webdriver
 from selenium.webdriver.common.by import By
 
 driver = webdriver.Firefox()
@@ -164,7 +180,7 @@
 
 for e in elements:
     print(e.text)
-  
using OpenQA.Selenium;
+  
using OpenQA.Selenium;
 using OpenQA.Selenium.Firefox;
 using System.Collections.Generic;
 
@@ -188,9 +204,9 @@
   }
  }
 }
-  
      elements = driver.find_elements(:tag_name,'p')
+  
      elements = driver.find_elements(:tag_name,'p')
          elements.each { |e| puts e.text }
const {Builder, By} = require('selenium-webdriver');
+View full example on GitHub
const {Builder, By} = require('selenium-webdriver');
 (async function example() {
     let driver = await new Builder().forBrowser('firefox').build();
     try {
@@ -208,7 +224,7 @@
     }
 })();
   
-
import org.openqa.selenium.By
+
import org.openqa.selenium.By
 import org.openqa.selenium.firefox.FirefoxDriver
 
 fun main() {
@@ -225,13 +241,13 @@
     }
 }
   

Localizar Elementos em um Elemento

Ele é usado para localizar a lista de WebElements filhos correspondentes dentro do contexto do elemento pai. -Para realizar isso, o WebElement pai é encadeado com o ‘findElements’ para acessar seus elementos filhos.

  import org.openqa.selenium.By;
+Para realizar isso, o WebElement pai é encadeado com o ‘findElements’ para acessar seus elementos filhos.

  import org.openqa.selenium.By;
   import org.openqa.selenium.WebDriver;
   import org.openqa.selenium.WebElement;
   import org.openqa.selenium.chrome.ChromeDriver;
@@ -256,7 +272,7 @@
           }
       }
   }
-  
##get elements from parent element using TAG_NAME
+  
##get elements from parent element using TAG_NAME
 
     # Obtém o elemento com o nome da tag 'div'
 element = driver.find_element(By.TAG_NAME, 'div')
@@ -276,7 +292,7 @@
 elements  = driver.find_elements(By.XPATH, './/li')
 for e in elements:
     print(e.text)
-  
using OpenQA.Selenium;
+  
using OpenQA.Selenium;
 using OpenQA.Selenium.Chrome;
 using System.Collections.Generic;
 
@@ -301,10 +317,10 @@
   }
  }
 }
-  
      element = driver.find_element(:tag_name,'div')
+  
      element = driver.find_element(:tag_name,'div')
          elements = element.find_elements(:tag_name,'p')
          elements.each { |e| puts e.text }
  const {Builder, By} = require('selenium-webdriver');
+View full example on GitHub
  const {Builder, By} = require('selenium-webdriver');
 
   (async function example() {
       let driver = new Builder()
@@ -323,7 +339,7 @@
       }
   })();
   
-
  import org.openqa.selenium.By
+
  import org.openqa.selenium.By
   import org.openqa.selenium.chrome.ChromeDriver
 
   fun main() {
@@ -343,13 +359,13 @@
           driver.quit()
       }
   }
-  

Obter elemento ativo

Ele é usado para rastrear (ou) encontrar um elemento DOM que tem o foco no contexto de navegação atual.

  import org.openqa.selenium.*;
+  

Obter elemento ativo

Ele é usado para rastrear (ou) encontrar um elemento DOM que tem o foco no contexto de navegação atual.

  import org.openqa.selenium.*;
   import org.openqa.selenium.chrome.ChromeDriver;
 
   public class activeElementTest {
@@ -367,7 +383,7 @@
       }
     }
   }
-  
  from selenium import webdriver
+  
  from selenium import webdriver
   from selenium.webdriver.common.by import By
 
   driver = webdriver.Chrome()
@@ -377,7 +393,7 @@
     # Obter atributo do elemento atualmente ativo
   attr = driver.switch_to.active_element.get_attribute("title")
   print(attr)
-  
    using OpenQA.Selenium;
+  
    using OpenQA.Selenium;
     using OpenQA.Selenium.Chrome;
 
     namespace ActiveElement {
@@ -398,9 +414,9 @@
       }
      }
     }
-  
      driver.find_element(css: '[name="q"]').send_keys('webElement')
+  
      driver.find_element(css: '[name="q"]').send_keys('webElement')
         attr = driver.switch_to.active_element.attribute('title')
  const {Builder, By} = require('selenium-webdriver');
+View full example on GitHub
  const {Builder, By} = require('selenium-webdriver');
 
   (async function example() {
       let driver = await new Builder().forBrowser('chrome').build();
@@ -412,7 +428,7 @@
       console.log(`${attr}`)
   })();
   
-
  import org.openqa.selenium.By
+
  import org.openqa.selenium.By
   import org.openqa.selenium.chrome.ChromeDriver
 
   fun main() {
diff --git a/pt-br/documentation/webdriver/elements/finders/index.html b/pt-br/documentation/webdriver/elements/finders/index.html
index 4dddc7bba4e8..625043c5c0a7 100644
--- a/pt-br/documentation/webdriver/elements/finders/index.html
+++ b/pt-br/documentation/webdriver/elements/finders/index.html
@@ -1,7 +1,7 @@
 Encontrando Elementos Web | Selenium
 

Encontrando Elementos Web

Localizando elementos com base nos valores providenciados pelo localizador.

Um dos aspectos mais fundamentais do uso do Selenium é obter referências de elementos para trabalhar. + Print entire section



Encontrando Elementos Web

Localizando elementos com base nos valores providenciados pelo localizador.

Um dos aspectos mais fundamentais do uso do Selenium é obter referências de elementos para trabalhar. O Selenium oferece várias estratégias de localizador para identificar exclusivamente um elemento. Há muitas maneiras de usar os localizadores em cenários complexos. Para os propósitos desta documentação, vamos considerar este trecho de HTML:

<ol id="vegetables">
@@ -71,51 +71,67 @@
   

Java e C#
As classes WebDriver, WebElement e ShadowRoot todas implementam o SearchContext interface, que é considerada uma role-based interface(interface baseada em função). As interfaces baseadas em função permitem determinar se uma determinada implementação de driver suporta um recurso específico. Essas interfaces são claramente definidas e tentam -aderir a ter apenas um único papel de responsabilidade.

Localizador otimizado

Uma pesquisa aninhada pode não ser a estratégia de localização mais eficaz, pois requer dois +aderir a ter apenas um único papel de responsabilidade.

Evaluating the Shadow DOM

The Shadow DOM is an encapsulated DOM tree hidden inside an element. +With the release of v96 in Chromium Browsers, Selenium can now allow you to access this tree +with easy-to-use shadow root methods. NOTE: These methods require Selenium 4.0 or greater.

Move Code

WebElement shadowHost = driver.findElement(By.cssSelector("#shadow_host"));
+SearchContext shadowRoot = shadowHost.getShadowRoot();
+WebElement shadowContent = shadowRoot.findElement(By.cssSelector("#shadow_content"));
shadow_host = driver.find_element(By.CSS_SELECTOR, '#shadow_host')
+shadow_root = shadow_host.shadow_root
+shadow_content = shadow_root.find_element(By.CSS_SELECTOR, '#shadow_content')
var shadowHost = _driver.FindElement(By.CssSelector("#shadow_host"));
+var shadowRoot = shadowHost.GetShadowRoot();
+var shadowContent = shadowRoot.FindElement(By.CssSelector("#shadow_content"));
shadow_host = @driver.find_element(css: '#shadow_host') +shadow_root = shadow_host.shadow_root +shadow_content = shadow_root.find_element(css: '#shadow_content')

Localizador otimizado

Uma pesquisa aninhada pode não ser a estratégia de localização mais eficaz, pois requer dois comandos separados a serem emitidos para o navegador.

Para melhorar um pouco o desempenho, podemos usar CSS ou XPath para encontrar esse elemento com um único comando. Veja as sugestões de estratégia do localizador na nossa sessão de -Práticas de teste incentivadas.

Para esse exemplo, utilizaremos o CSS Selector:

WebElement fruit = driver.findElement(By.cssSelector("#fruits .tomatoes"));
-  
fruit = driver.find_element(By.CSS_SELECTOR,"#fruits .tomatoes")
-  
var fruit = driver.FindElement(By.CssSelector("#fruits .tomatoes"));
-  
      fruit = driver.find_element(css: '#fruits .tomatoes')
const fruit = await driver.findElement(By.css('#fruits .tomatoes'));
-  
-
val fruit = driver.findElement(By.cssSelector("#fruits .tomatoes"))
-  

Todos os elementos correspondentes

Existem vários casos de uso para a necessidade de obter referências a todos os elementos que correspondem a um localizador, em vez -do que apenas o primeiro. Os métodos plurais find elements retornam uma coleção de referências de elementos. -Se não houver correspondências, uma lista vazia será retornada. Nesse caso, -referências a todos os itens da lista de frutas e vegetais serão devolvidas em uma coleção.

List<WebElement> plants = driver.findElements(By.tagName("li"));
-  
plants = driver.find_elements(By.TAG_NAME, "li")
-  
IReadOnlyList<IWebElement> plants = driver.FindElements(By.TagName("li"));
-  
      plants = driver.find_elements(tag_name: 'li')
const plants = await driver.findElements(By.tagName('li'));
+Kotlin
WebElement fruit = driver.findElement(By.cssSelector("#fruits .tomatoes"));
+  
fruit = driver.find_element(By.CSS_SELECTOR,"#fruits .tomatoes")
+  
var fruit = driver.FindElement(By.CssSelector("#fruits .tomatoes"));
+  
      fruit = driver.find_element(css: '#fruits .tomatoes')
const fruit = await driver.findElement(By.css('#fruits .tomatoes'));
   
-
val plants: List<WebElement> = driver.findElements(By.tagName("li"))
-  

Obter Elemento

Muitas vezes você obterá uma coleção de elementos, mas quer trabalhar apenas com um elemento específico, o que significa que você -precisa iterar sobre a coleção e identificar o que você deseja.

val fruit = driver.findElement(By.cssSelector("#fruits .tomatoes"))
+  

Todos os elementos correspondentes

Existem vários casos de uso para a necessidade de obter referências a todos os elementos que correspondem a um localizador, em vez +do que apenas o primeiro. Os métodos plurais find elements retornam uma coleção de referências de elementos. +Se não houver correspondências, uma lista vazia será retornada. Nesse caso, +referências a todos os itens da lista de frutas e vegetais serão devolvidas em uma coleção.

List<WebElement> elements = driver.findElements(By.tagName("li"));
+Kotlin
List<WebElement> plants = driver.findElements(By.tagName("li"));
+  
plants = driver.find_elements(By.TAG_NAME, "li")
+  
IReadOnlyList<IWebElement> plants = driver.FindElements(By.TagName("li"));
+  
      plants = driver.find_elements(tag_name: 'li')
const plants = await driver.findElements(By.tagName('li'));
+  
+
val plants: List<WebElement> = driver.findElements(By.tagName("li"))
+  

Obter Elemento

Muitas vezes você obterá uma coleção de elementos, mas quer trabalhar apenas com um elemento específico, o que significa que você +precisa iterar sobre a coleção e identificar o que você deseja.

List<WebElement> elements = driver.findElements(By.tagName("li"));
 
 for (WebElement element : elements) {
     System.out.println("Paragraph text:" + element.getText());
 }
-  
from selenium import webdriver
+  
from selenium import webdriver
 from selenium.webdriver.common.by import By
 
 driver = webdriver.Firefox()
@@ -128,7 +144,7 @@
 
 for e in elements:
     print(e.text)
-  
using OpenQA.Selenium;
+  
using OpenQA.Selenium;
 using OpenQA.Selenium.Firefox;
 using System.Collections.Generic;
 
@@ -152,9 +168,9 @@
   }
  }
 }
-  
      elements = driver.find_elements(:tag_name,'p')
+  
      elements = driver.find_elements(:tag_name,'p')
          elements.each { |e| puts e.text }
const {Builder, By} = require('selenium-webdriver');
+View full example on GitHub
const {Builder, By} = require('selenium-webdriver');
 (async function example() {
     let driver = await new Builder().forBrowser('firefox').build();
     try {
@@ -172,7 +188,7 @@
     }
 })();
   
-
import org.openqa.selenium.By
+
import org.openqa.selenium.By
 import org.openqa.selenium.firefox.FirefoxDriver
 
 fun main() {
@@ -189,13 +205,13 @@
     }
 }
   

Localizar Elementos em um Elemento

Ele é usado para localizar a lista de WebElements filhos correspondentes dentro do contexto do elemento pai. -Para realizar isso, o WebElement pai é encadeado com o ‘findElements’ para acessar seus elementos filhos.

  import org.openqa.selenium.By;
+Para realizar isso, o WebElement pai é encadeado com o ‘findElements’ para acessar seus elementos filhos.

  import org.openqa.selenium.By;
   import org.openqa.selenium.WebDriver;
   import org.openqa.selenium.WebElement;
   import org.openqa.selenium.chrome.ChromeDriver;
@@ -220,7 +236,7 @@
           }
       }
   }
-  
##get elements from parent element using TAG_NAME
+  
##get elements from parent element using TAG_NAME
 
     # Obtém o elemento com o nome da tag 'div'
 element = driver.find_element(By.TAG_NAME, 'div')
@@ -240,7 +256,7 @@
 elements  = driver.find_elements(By.XPATH, './/li')
 for e in elements:
     print(e.text)
-  
using OpenQA.Selenium;
+  
using OpenQA.Selenium;
 using OpenQA.Selenium.Chrome;
 using System.Collections.Generic;
 
@@ -265,10 +281,10 @@
   }
  }
 }
-  
      element = driver.find_element(:tag_name,'div')
+  
      element = driver.find_element(:tag_name,'div')
          elements = element.find_elements(:tag_name,'p')
          elements.each { |e| puts e.text }
  const {Builder, By} = require('selenium-webdriver');
+View full example on GitHub
  const {Builder, By} = require('selenium-webdriver');
 
   (async function example() {
       let driver = new Builder()
@@ -287,7 +303,7 @@
       }
   })();
   
-
  import org.openqa.selenium.By
+
  import org.openqa.selenium.By
   import org.openqa.selenium.chrome.ChromeDriver
 
   fun main() {
@@ -307,13 +323,13 @@
           driver.quit()
       }
   }
-  

Obter elemento ativo

Ele é usado para rastrear (ou) encontrar um elemento DOM que tem o foco no contexto de navegação atual.

  import org.openqa.selenium.*;
+  

Obter elemento ativo

Ele é usado para rastrear (ou) encontrar um elemento DOM que tem o foco no contexto de navegação atual.

  import org.openqa.selenium.*;
   import org.openqa.selenium.chrome.ChromeDriver;
 
   public class activeElementTest {
@@ -331,7 +347,7 @@
       }
     }
   }
-  
  from selenium import webdriver
+  
  from selenium import webdriver
   from selenium.webdriver.common.by import By
 
   driver = webdriver.Chrome()
@@ -341,7 +357,7 @@
     # Obter atributo do elemento atualmente ativo
   attr = driver.switch_to.active_element.get_attribute("title")
   print(attr)
-  
    using OpenQA.Selenium;
+  
    using OpenQA.Selenium;
     using OpenQA.Selenium.Chrome;
 
     namespace ActiveElement {
@@ -362,9 +378,9 @@
       }
      }
     }
-  
      driver.find_element(css: '[name="q"]').send_keys('webElement')
+  
      driver.find_element(css: '[name="q"]').send_keys('webElement')
         attr = driver.switch_to.active_element.attribute('title')
  const {Builder, By} = require('selenium-webdriver');
+View full example on GitHub
  const {Builder, By} = require('selenium-webdriver');
 
   (async function example() {
       let driver = await new Builder().forBrowser('chrome').build();
@@ -376,7 +392,7 @@
       console.log(`${attr}`)
   })();
   
-
  import org.openqa.selenium.By
+
  import org.openqa.selenium.By
   import org.openqa.selenium.chrome.ChromeDriver
 
   fun main() {
@@ -392,5 +408,5 @@
           driver.quit()
       }
   }
-  

Development Partners

Selenium Level Sponsors

Support the Selenium Project

Learn more or view the full list of sponsors.

Development Partners

Selenium Level Sponsors

Support the Selenium Project

Learn more or view the full list of sponsors.

\ No newline at end of file diff --git a/pt-br/documentation/webdriver/getting_started/_print/index.html b/pt-br/documentation/webdriver/getting_started/_print/index.html index 8e6a9a27a819..d63d187e7bbd 100644 --- a/pt-br/documentation/webdriver/getting_started/_print/index.html +++ b/pt-br/documentation/webdriver/getting_started/_print/index.html @@ -47,13 +47,13 @@ testImplementation 'org.junit.jupiter:junit-jupiter-engine:5.11.0'

A mínima versão suportada do Python para cada versão do Selenium pode ser encontrada em Supported Python Versions no PyPi

Existe muitas formas diferentes de instalar Selenium.

Pip

pip install selenium
-

Download

Como uma alternativa você pode baixar o código fonte PyPI +


Download

Como uma alternativa você pode baixar o código fonte PyPI (selenium-x.x.x.tar.gz) e instalar usando setup.py:

python setup.py install
-

Exigir em um projeto

Para usar em um projeto, adicione no arquivo requirements.txt.

selenium==4.23.1

Exigir em um projeto

Para usar em um projeto, adicione no arquivo requirements.txt.

selenium==4.23.1

Uma lista com todos os frameworks suportados para cada versão do Selenium pode ser encontrada em Nuget

Existe algumas opções para instalar o Selenium.

Packet Manager

Install-Package Selenium.WebDriver
-

.NET CLI

dotnet add package Selenium.WebDriver
-

CSProj

No arquivo csproj do seu projeto, especifique a dependência como PackageReference no ItemGroup:

      <PackageReference Include="Selenium.WebDriver" Version="4.23.0" />

.NET CLI

dotnet add package Selenium.WebDriver
+

CSProj

No arquivo csproj do seu projeto, especifique a dependência como PackageReference no ItemGroup:

      <PackageReference Include="Selenium.WebDriver" Version="4.23.0" />

Considerações adicionais

Outras observações para usar o Visual Studio Code (vscode) e C#

Instale a versão compatível do .NET SDK conforme a seção acima. Instale também as extensões do vscode (Ctrl-Shift-X) para C# e NuGet. Siga as instruções aqui para criar e rodar o seu projeto de “Hello World” no console usando C#.

Você também pode criar um projeto inicial do NUnit usando a linha de comando dotnet new NUnit. @@ -71,10 +71,10 @@ Aperte Enter e selecione a versão. Agora você pode usar os exemplos da documentação relacionados ao C# com o vscode.

Você pode ver a minima versão suportada do Ruby para cada versão do Selenium em rubygems.org

O Selenium pode ser instalado de duas formas diferentes.

Instalação manual

gem install selenium-webdriver
-

Adicione para o gemfile do projeto

gem 'selenium-devtools', '= 0.127.0'

Adicione para o gemfile do projeto

gem 'selenium-devtools', '= 0.127.0'

Você pode encontrar a mínima versão suportada do Node para cada versão do Selenium na seção Node Support Policy no site npmjs

Selenium é normalmente instalado usando npm.

Instalação local

npm install selenium-webdriver
-

Adicione ao seu projeto

No package.json do seu projeto, adicione os requisitos em dependencies:

        "mocha": "10.7.3"

Adicione ao seu projeto

No package.json do seu projeto, adicione os requisitos em dependencies:

        "mocha": "10.7.3"
Use as ligações Java para Kotlin.

Próximo passo

Programando o seu primeiro script Selenium

2 - Programe o seu primeiro script Selenium

Instruções passo a passo para programar um script Selenium

Assim que você tiver o Selenium instalado, você estará pronto para programar códigos Selenium.

Oito Componentes Básicos

Tudo que o Selenium faz é enviar comandos ao navegador de internet para fazer algo ou solicitar informações dele. A maior parte do que você irá fazer com o Selenium é uma combinação desses comandos básicos.

Click on the link to “View full example on GitHub” to see the code in context.

1. Iniciando uma sessão

Para ter mais detalhes sobre como iniciar uma sessão, leia nossa documentação em driver sessions

		String title = driver.getTitle();
 		assertEquals("Web form", title);
    title = driver.title
-    assert title == "Web form"
            var title = driver.Title;
             Assert.AreEqual("Web form", title);
    title = @driver.title
@@ -267,9 +267,9 @@
 View full example on GitHub

Set Up

def setup():
     driver = webdriver.Chrome()
     driver.get("https://www.selenium.dev/selenium/web/web-form.html")
-    return driver

Tear Down

def teardown(driver):
-    driver.quit()

Set Up

  before do
     @driver = Selenium::WebDriver.for :chrome
   end
@@ -353,9 +353,7 @@ def test_eight_components(): - driver = webdriver.Chrome() - - driver.get("https://www.selenium.dev/selenium/web/web-form.html") + driver = setup() title = driver.title assert title == "Web form" @@ -372,7 +370,7 @@ value = message.text assert value == "Received!" - driver.quit() + teardown(driver) def setup(): driver = webdriver.Chrome() diff --git a/pt-br/documentation/webdriver/getting_started/install_library/index.html b/pt-br/documentation/webdriver/getting_started/install_library/index.html index c8aba0f6ee75..0758c7b3a80a 100644 --- a/pt-br/documentation/webdriver/getting_started/install_library/index.html +++ b/pt-br/documentation/webdriver/getting_started/install_library/index.html @@ -1,7 +1,7 @@ Instalando bibliotecas do Selenium | Selenium

Uma lista com todos os frameworks suportados para cada versão do Selenium pode ser encontrada em Nuget

Existe algumas opções para instalar o Selenium.

Packet Manager

Install-Package Selenium.WebDriver
-

.NET CLI

dotnet add package Selenium.WebDriver
-

CSProj

No arquivo csproj do seu projeto, especifique a dependência como PackageReference no ItemGroup:

      <PackageReference Include="Selenium.WebDriver" Version="4.23.0" />

.NET CLI

dotnet add package Selenium.WebDriver
+

CSProj

No arquivo csproj do seu projeto, especifique a dependência como PackageReference no ItemGroup:

      <PackageReference Include="Selenium.WebDriver" Version="4.23.0" />

Considerações adicionais

Outras observações para usar o Visual Studio Code (vscode) e C#

Instale a versão compatível do .NET SDK conforme a seção acima. Instale também as extensões do vscode (Ctrl-Shift-X) para C# e NuGet. Siga as instruções aqui para criar e rodar o seu projeto de “Hello World” no console usando C#.

Você também pode criar um projeto inicial do NUnit usando a linha de comando dotnet new NUnit. @@ -55,9 +55,9 @@ Aperte Enter e selecione a versão. Agora você pode usar os exemplos da documentação relacionados ao C# com o vscode.

Você pode ver a minima versão suportada do Ruby para cada versão do Selenium em rubygems.org

O Selenium pode ser instalado de duas formas diferentes.

Instalação manual

gem install selenium-webdriver
-

Adicione para o gemfile do projeto

gem 'selenium-devtools', '= 0.127.0'

Adicione para o gemfile do projeto

gem 'selenium-devtools', '= 0.127.0'

Você pode encontrar a mínima versão suportada do Node para cada versão do Selenium na seção Node Support Policy no site npmjs

Selenium é normalmente instalado usando npm.

Instalação local

npm install selenium-webdriver
-

Adicione ao seu projeto

No package.json do seu projeto, adicione os requisitos em dependencies:

        "mocha": "10.7.3"
Use as ligações Java para Kotlin.

Próximo passo

Programando o seu primeiro script Selenium

Development Partners

Selenium Level Sponsors

Use as ligações Java para Kotlin.

Próximo passo

Programando o seu primeiro script Selenium

Última modificação August 26, 2024: Added breakpoints b/w coding examples in Installing Selenium (#1892) (3688b1e10e6)

Development Partners

Selenium Level Sponsors

Support the Selenium Project

Learn more or view the full list of sponsors.

\ No newline at end of file diff --git a/pt-br/documentation/webdriver/getting_started/using_selenium/index.html b/pt-br/documentation/webdriver/getting_started/using_selenium/index.html index 0d53dacf2b2b..93501c150eba 100644 --- a/pt-br/documentation/webdriver/getting_started/using_selenium/index.html +++ b/pt-br/documentation/webdriver/getting_started/using_selenium/index.html @@ -1,7 +1,7 @@ Organizando e executando o código Selenium | Selenium

查询网络元素

根据提供的定位值定位元素.

One of the most fundamental aspects of using Selenium is obtaining element references to work with. + 整节打印



查询网络元素

根据提供的定位值定位元素.

One of the most fundamental aspects of using Selenium is obtaining element references to work with. Selenium offers a number of built-in locator strategies to uniquely identify an element. There are many ways to use the locators in very advanced scenarios. For the purposes of this documentation, let’s consider this HTML snippet:

<ol id="vegetables">
@@ -70,51 +70,67 @@
   

Java and C#
WebDriver, WebElement and ShadowRoot classes all implement a SearchContext interface, which is considered a role-based interface. Role-based interfaces allow you to determine whether a particular driver implementation supports a given feature. These interfaces are clearly defined and try -to adhere to having only a single role of responsibility.

Optimized locator

A nested lookup might not be the most effective location strategy since it requires two +to adhere to having only a single role of responsibility.

Evaluating the Shadow DOM

The Shadow DOM is an encapsulated DOM tree hidden inside an element. +With the release of v96 in Chromium Browsers, Selenium can now allow you to access this tree +with easy-to-use shadow root methods. NOTE: These methods require Selenium 4.0 or greater.

Move Code

WebElement shadowHost = driver.findElement(By.cssSelector("#shadow_host"));
+SearchContext shadowRoot = shadowHost.getShadowRoot();
+WebElement shadowContent = shadowRoot.findElement(By.cssSelector("#shadow_content"));
shadow_host = driver.find_element(By.CSS_SELECTOR, '#shadow_host')
+shadow_root = shadow_host.shadow_root
+shadow_content = shadow_root.find_element(By.CSS_SELECTOR, '#shadow_content')
var shadowHost = _driver.FindElement(By.CssSelector("#shadow_host"));
+var shadowRoot = shadowHost.GetShadowRoot();
+var shadowContent = shadowRoot.FindElement(By.CssSelector("#shadow_content"));
shadow_host = @driver.find_element(css: '#shadow_host') +shadow_root = shadow_host.shadow_root +shadow_content = shadow_root.find_element(css: '#shadow_content')

Optimized locator

A nested lookup might not be the most effective location strategy since it requires two separate commands to be issued to the browser.

To improve the performance slightly, we can use either CSS or XPath to find this element in a single command. See the Locator strategy suggestions in our -Encouraged test practices section.

For this example, we’ll use a CSS Selector:

WebElement fruit = driver.findElement(By.cssSelector("#fruits .tomatoes"));
-  
fruit = driver.find_element(By.CSS_SELECTOR,"#fruits .tomatoes")
-  
var fruit = driver.FindElement(By.CssSelector("#fruits .tomatoes"));
-  
      fruit = driver.find_element(css: '#fruits .tomatoes')
const fruit = await driver.findElement(By.css('#fruits .tomatoes'));
-  
-
val fruit = driver.findElement(By.cssSelector("#fruits .tomatoes"))
-  

All matching elements

There are several use cases for needing to get references to all elements that match a locator, rather -than just the first one. The plural find elements methods return a collection of element references. -If there are no matches, an empty list is returned. In this case, -references to all fruits and vegetable list items will be returned in a collection.

List<WebElement> plants = driver.findElements(By.tagName("li"));
-  
plants = driver.find_elements(By.TAG_NAME, "li")
-  
IReadOnlyList<IWebElement> plants = driver.FindElements(By.TagName("li"));
-  
      plants = driver.find_elements(tag_name: 'li')
const plants = await driver.findElements(By.tagName('li'));
+Kotlin
WebElement fruit = driver.findElement(By.cssSelector("#fruits .tomatoes"));
+  
fruit = driver.find_element(By.CSS_SELECTOR,"#fruits .tomatoes")
+  
var fruit = driver.FindElement(By.CssSelector("#fruits .tomatoes"));
+  
      fruit = driver.find_element(css: '#fruits .tomatoes')
const fruit = await driver.findElement(By.css('#fruits .tomatoes'));
   
-
val plants: List<WebElement> = driver.findElements(By.tagName("li"))
-  

Get element

Often you get a collection of elements but want to work with a specific element, which means you -need to iterate over the collection and identify the one you want.

val fruit = driver.findElement(By.cssSelector("#fruits .tomatoes"))
+  

All matching elements

There are several use cases for needing to get references to all elements that match a locator, rather +than just the first one. The plural find elements methods return a collection of element references. +If there are no matches, an empty list is returned. In this case, +references to all fruits and vegetable list items will be returned in a collection.

List<WebElement> elements = driver.findElements(By.tagName("li"));
+Kotlin
List<WebElement> plants = driver.findElements(By.tagName("li"));
+  
plants = driver.find_elements(By.TAG_NAME, "li")
+  
IReadOnlyList<IWebElement> plants = driver.FindElements(By.TagName("li"));
+  
      plants = driver.find_elements(tag_name: 'li')
const plants = await driver.findElements(By.tagName('li'));
+  
+
val plants: List<WebElement> = driver.findElements(By.tagName("li"))
+  

Get element

Often you get a collection of elements but want to work with a specific element, which means you +need to iterate over the collection and identify the one you want.

List<WebElement> elements = driver.findElements(By.tagName("li"));
 
 for (WebElement element : elements) {
     System.out.println("Paragraph text:" + element.getText());
 }
-  
from selenium import webdriver
+  
from selenium import webdriver
 from selenium.webdriver.common.by import By
 
 driver = webdriver.Firefox()
@@ -127,7 +143,7 @@
 
 for e in elements:
     print(e.text)
-  
using OpenQA.Selenium;
+  
using OpenQA.Selenium;
 using OpenQA.Selenium.Firefox;
 using System.Collections.Generic;
 
@@ -151,9 +167,9 @@
   }
  }
 }
-  
      elements = driver.find_elements(:tag_name,'p')
+  
      elements = driver.find_elements(:tag_name,'p')
          elements.each { |e| puts e.text }
const {Builder, By} = require('selenium-webdriver');
+View full example on GitHub
const {Builder, By} = require('selenium-webdriver');
 (async function example() {
     let driver = await new Builder().forBrowser('firefox').build();
     try {
@@ -171,7 +187,7 @@
     }
 })();
   
-
import org.openqa.selenium.By
+
import org.openqa.selenium.By
 import org.openqa.selenium.firefox.FirefoxDriver
 
 fun main() {
@@ -188,13 +204,13 @@
     }
 }
   

Find Elements From Element

It is used to find the list of matching child WebElements within the context of parent element. -To achieve this, the parent WebElement is chained with ‘findElements’ to access child elements

  import org.openqa.selenium.By;
+To achieve this, the parent WebElement is chained with ‘findElements’ to access child elements

  import org.openqa.selenium.By;
   import org.openqa.selenium.WebDriver;
   import org.openqa.selenium.WebElement;
   import org.openqa.selenium.chrome.ChromeDriver;
@@ -219,7 +235,7 @@
           }
       }
   }
-  
from selenium import webdriver
+  
from selenium import webdriver
 from selenium.webdriver.common.by import By
 
 driver = webdriver.Chrome()
@@ -244,7 +260,7 @@
 elements  = driver.find_elements(By.XPATH, './/li')
 for e in elements:
     print(e.text)
-  
using OpenQA.Selenium;
+  
using OpenQA.Selenium;
 using OpenQA.Selenium.Chrome;
 using System.Collections.Generic;
 
@@ -269,10 +285,10 @@
   }
  }
 }
-  
      element = driver.find_element(:tag_name,'div')
+  
      element = driver.find_element(:tag_name,'div')
          elements = element.find_elements(:tag_name,'p')
          elements.each { |e| puts e.text }
  const {Builder, By} = require('selenium-webdriver');
+View full example on GitHub
  const {Builder, By} = require('selenium-webdriver');
 
   (async function example() {
       let driver = new Builder()
@@ -291,7 +307,7 @@
       }
   })();
   
-
  import org.openqa.selenium.By
+
  import org.openqa.selenium.By
   import org.openqa.selenium.chrome.ChromeDriver
 
   fun main() {
@@ -311,13 +327,13 @@
           driver.quit()
       }
   }
-  

Get Active Element

It is used to track (or) find DOM element which has the focus in the current browsing context.

  import org.openqa.selenium.*;
+  

Get Active Element

It is used to track (or) find DOM element which has the focus in the current browsing context.

  import org.openqa.selenium.*;
   import org.openqa.selenium.chrome.ChromeDriver;
 
   public class activeElementTest {
@@ -335,7 +351,7 @@
       }
     }
   }
-  
  from selenium import webdriver
+  
  from selenium import webdriver
   from selenium.webdriver.common.by import By
 
   driver = webdriver.Chrome()
@@ -345,7 +361,7 @@
     # Get attribute of current active element
   attr = driver.switch_to.active_element.get_attribute("title")
   print(attr)
-  
    using OpenQA.Selenium;
+  
    using OpenQA.Selenium;
     using OpenQA.Selenium.Chrome;
 
     namespace ActiveElement {
@@ -366,9 +382,9 @@
       }
      }
     }
-  
      driver.find_element(css: '[name="q"]').send_keys('webElement')
+  
      driver.find_element(css: '[name="q"]').send_keys('webElement')
         attr = driver.switch_to.active_element.attribute('title')
  const {Builder, By} = require('selenium-webdriver');
+View full example on GitHub
  const {Builder, By} = require('selenium-webdriver');
 
   (async function example() {
       let driver = await new Builder().forBrowser('chrome').build();
@@ -380,7 +396,7 @@
       console.log(`${attr}`)
   })();
   
-
  import org.openqa.selenium.By
+
  import org.openqa.selenium.By
   import org.openqa.selenium.chrome.ChromeDriver
 
   fun main() {
@@ -396,5 +412,5 @@
           driver.quit()
       }
   }
-  

Development Partners

Selenium Level Sponsors

Support the Selenium Project

Learn more or view the full list of sponsors.

最后修改 August 26, 2024: added shadow dom documentation to finders in all translations #1070 (#1887)[deploy site] (bb164c33902)

Development Partners

Selenium Level Sponsors

Support the Selenium Project

Learn more or view the full list of sponsors.

\ No newline at end of file diff --git a/zh-cn/documentation/webdriver/getting_started/_print/index.html b/zh-cn/documentation/webdriver/getting_started/_print/index.html index 8d065185ca3b..95cf0e68d9f3 100644 --- a/zh-cn/documentation/webdriver/getting_started/_print/index.html +++ b/zh-cn/documentation/webdriver/getting_started/_print/index.html @@ -41,13 +41,13 @@ testImplementation 'org.junit.jupiter:junit-jupiter-engine:5.11.0'

该库所支持的Python版本最低版本可以在 支持的Python版本 章节中找到 PyPi

这里提供了几种不同的方式来安装 Selenium .

Pip

pip install selenium
-

下载

此外你可以从这里下载 PyPI source archive +


下载

此外你可以从这里下载 PyPI source archive (selenium-x.x.x.tar.gz) 并通过: setup.py 文件安装:

python setup.py install
-

在项目中使用

为了在项目中使用它,需要将它添加到 requirements.txt 文件中:

selenium==4.23.1
+

在项目中使用

为了在项目中使用它,需要将它添加到 requirements.txt 文件中:

selenium==4.23.1
View full example on GitHub

Selenium 所支持的所有平台的列表一览 见诸于 Nuget

该处阐述了一些安装Selenium的选项.

包管理器

Install-Package Selenium.WebDriver
-

.NET CLI

dotnet add package Selenium.WebDriver
-

CSProj

csproj 文件里, 具体的依赖 PackageReference(包参数) 位于 ItemGroup (项目组)中:

      <PackageReference Include="Selenium.WebDriver" Version="4.23.0" />
+

.NET CLI

dotnet add package Selenium.WebDriver
+

CSProj

csproj 文件里, 具体的依赖 PackageReference(包参数) 位于 ItemGroup (项目组)中:

      <PackageReference Include="Selenium.WebDriver" Version="4.23.0" />
View full example on GitHub

其他附加思虑事项

更多的注意事项,适用于使用 Visual Studio Code (vscode) 和 C#

安装兼容的 .NET SDK 作为章节的先决条件 同时安装 vscode 的扩展 (Ctrl-Shift-X)以适配 C# 和 NuGet 可以遵照此处进行 操作指南 @@ -66,11 +66,11 @@ 按下回车并选择版本. 现在你可以使用说明文档中关于 C# vscode下的案例了.

你可以查看 Selenium 对 Ruby 版本支持和最低支持. 具体位于 rubygems.org

Selenium 可以使用两种不同方法安装.

手动安装

gem install selenium-webdriver
-

加入项目的 gemfile

gem 'selenium-devtools', '= 0.127.0'
+

加入项目的 gemfile

gem 'selenium-devtools', '= 0.127.0'
View full example on GitHub

You can find the minimum required version of Node for any given version of Selenium in the 你可以在此查看 Selenium 对 Node 的版本支持情况 位于 Node Support Policy 中的相关章节 npmjs

Selenium is typically installed using npm.

本地安装

npm install selenium-webdriver
-

加入项目

在你的项目 package.json, 必须加入到 dependencies:

        "mocha": "10.7.3"
+

加入项目

在你的项目 package.json, 必须加入到 dependencies:

        "mocha": "10.7.3"
View full example on GitHub
Use the Java bindings for Kotlin.

下一步

创建你的第一个Selenium脚本

2 - 编写第一个Selenium脚本

逐步构建一个Selenium脚本的说明

当你完成 Selenium安装 后, 便可以开始书写Selenium脚本了.

八个基本组成部分

Selenium所做的一切, 就是发送给浏览器命令, 用以执行某些操作或为信息发送请求. @@ -101,7 +101,7 @@ View full example on GitHub

driver.get('https://www.selenium.dev/selenium/web/web-form.html')
View full example on GitHub
    await driver.get('https://www.selenium.dev/selenium/web/web-form.html');
View full example on GitHub
        driver.get("https://www.selenium.dev/selenium/web/web-form.html")
-View full example on GitHub

3. 请求 浏览器信息

您可以请求一系列关于浏览器的信息 , +View full example on GitHub

3. 请求 浏览器信息

您可以请求一系列关于浏览器的信息 , 包括窗口句柄、浏览器尺寸/位置、cookie、警报等.

		String title = driver.getTitle();
 		assertEquals("Web form", title);
    title = driver.title
-    assert title == "Web form"
            var title = driver.Title;
             Assert.AreEqual("Web form", title);
    title = @driver.title
@@ -258,9 +258,9 @@
 View full example on GitHub

Set Up

def setup():
     driver = webdriver.Chrome()
     driver.get("https://www.selenium.dev/selenium/web/web-form.html")
-    return driver

Tear Down

def teardown(driver):
-    driver.quit()

Add Example

Set Up

  before do
     @driver = Selenium::WebDriver.for :chrome
   end

编写第一个Selenium脚本

逐步构建一个Selenium脚本的说明

当你完成 Selenium安装 后, 便可以开始书写Selenium脚本了.

八个基本组成部分

Selenium所做的一切, + 整节打印



编写第一个Selenium脚本

逐步构建一个Selenium脚本的说明

当你完成 Selenium安装 后, 便可以开始书写Selenium脚本了.

八个基本组成部分

Selenium所做的一切, 就是发送给浏览器命令, 用以执行某些操作或为信息发送请求. 您将使用Selenium执行的大部分操作, @@ -45,7 +45,7 @@ View full example on GitHub

driver.get('https://www.selenium.dev/selenium/web/web-form.html')
    await driver.get('https://www.selenium.dev/selenium/web/web-form.html');
        driver.get("https://www.selenium.dev/selenium/web/web-form.html")

3. 请求 浏览器信息

您可以请求一系列关于浏览器的信息 , +View full example on GitHub

3. 请求 浏览器信息

您可以请求一系列关于浏览器的信息 , 包括窗口句柄、浏览器尺寸/位置、cookie、警报等.