这是本节的多页打印视图。
点击此处打印 .
返回本页常规视图 .
入门指南 如果你是Selenium的新手, 我们有一些资源帮助你快速入门.
Selenium 通过使用 WebDriver 支持市场上所有主流浏览器的自动化。
WebDriver 是一个 API 和协议,它定义了一个语言中立的接口,用于控制 web 浏览器的行为。
每个浏览器都有一个特定的 WebDriver 实现,称为驱动程序。
驱动程序是负责委派给浏览器的组件,并处理与 Selenium 和浏览器之间的通信。
这种分离是有意识地努力让浏览器供应商为其浏览器的实现负责的一部分。
Selenium 在可能的情况下使用这些第三方驱动程序,
但是在这些驱动程序不存在的情况下,它也提供了由项目自己维护的驱动程序。
Selenium 框架通过一个面向用户的界面将所有这些部分连接在一起,
该界面允许透明地使用不同的浏览器后端,
从而实现跨浏览器和跨平台自动化。
Selenium的设置与其他商业工具有很大不同.
在开始编写 Selenium 代码之前,
您必须安装所选语言的相关类库,
目标浏览器的驱动程序.
请点击以下链接,开始使用 Selenium WebDriver.
如果您希望从低代码/录制和播放工具开始,请查看
Selenium IDE
开始工作后,如果想扩展您的测试,请查看
Selenium Grid .
1 - 安装Selenium类库 配置自动化的浏览器.
首先,您需要为自动化项目安装 Selenium 绑定库。
库的安装过程取决于您选择使用的语言。
请求对应的程序语言
Java
Python
CSharp
Ruby
JavaScript
Kotlin 查看该库所支持java的最低版本 here .
应熟练掌握build tool以安装支持java的Selenium库
Maven 具体的依赖位于项目中的 pom.xml
文件:
<details class="mt-3">
<summary>Show full example</summary>
<div class="pt-2">
<div class="highlight"><pre tabindex="0" style="background-color:#f8f8f8;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-xml" data-lang="xml"><span style="display:flex;"><span><span style="color:#8f5902;font-style:italic"><?xml version="1.0" encoding="UTF-8"?></span>
<project xmlns= "http://maven.apache.org/POM/4.0.0"
xmlns:xsi= "http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation= "http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd" >
<modelVersion> 4.0.0</modelVersion>
<groupId> dev.selenium</groupId>
<artifactId> selenium-examples</artifactId>
<version> 1.0.0</version>
<properties>
<surefire.parallel> 1</surefire.parallel>
<maven.compiler.source> 17</maven.compiler.source>
<maven.compiler.target> 17</maven.compiler.target>
<project.build.sourceEncoding> UTF-8</project.build.sourceEncoding>
<selenium.version> 4.31.0</selenium.version>
</properties>
<repositories>
<repository>
<id> sonatype-nexus-snapshots</id>
<url> https://oss.sonatype.org/content/repositories/snapshots/ </url>
<snapshots>
<enabled> true</enabled>
</snapshots>
</repository>
</repositories>
<dependencies>
<dependency>
<groupId> org.seleniumhq.selenium</groupId>
<artifactId> selenium-java</artifactId>
<version> ${selenium.version}</version>
</dependency>
<dependency>
<groupId> org.seleniumhq.selenium</groupId>
<artifactId> selenium-grid</artifactId>
<version> ${selenium.version}</version>
</dependency>
<dependency>
<groupId> org.junit.jupiter</groupId>
<artifactId> junit-jupiter-engine</artifactId>
<version> 5.12.1</version>
<scope> test</scope>
</dependency>
<dependency>
<groupId> com.titusfortner</groupId>
<artifactId> selenium-logger</artifactId>
<version> 2.4.0</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId> org.apache.maven.plugins</groupId>
<artifactId> maven-surefire-plugin</artifactId>
<version> 3.5.3</version>
<configuration>
<properties>
<configurationParameters>
junit.jupiter.execution.parallel.enabled = true
junit.jupiter.execution.parallel.mode.default = concurrent
junit.jupiter.execution.parallel.config.strategy = fixed
junit.jupiter.execution.parallel.config.fixed.parallelism = ${surefire.parallel}
junit.jupiter.execution.parallel.config.fixed.max-pool-size = ${surefire.parallel}
</configurationParameters>
</properties>
<rerunFailingTestsCount> 3</rerunFailingTestsCount>
</configuration>
</plugin>
</plugins>
</build>
</project>
<div class="text-end pb-2 mt-2">
<a href="https://github.com/SeleniumHQ/seleniumhq.github.io/blob/display_full/examples/java/pom.xml#L30-L34" target="_blank">
<i class="fas fa-external-link-alt pl-2"></i>
<strong>View full example on GitHub</strong>
</a>
</div>
Gradle 具体的依赖位于项目中的 build.gradle
文件中的 testImplementation
:
<details class="mt-3">
<summary>Show full example</summary>
<div class="pt-2">
<div class="highlight"><pre tabindex="0" style="background-color:#f8f8f8;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-gradle" data-lang="gradle"><span style="display:flex;"><span><span style="color:#000">plugins</span> <span style="color:#ce5c00;font-weight:bold">{</span>
id 'java'
}
group 'dev.selenium'
version '1.0-SNAPSHOT'
repositories {
mavenCentral ()
}
dependencies {
testImplementation 'org.seleniumhq.selenium:selenium-java:4.31.0'
testImplementation 'org.junit.jupiter:junit-jupiter-engine:5.12.1'
}
test {
useJUnitPlatform ()
}
<div class="text-end pb-2 mt-2">
<a href="https://github.com/SeleniumHQ/seleniumhq.github.io/blob/display_full/examples/java/build.gradle#L13-L14" target="_blank">
<i class="fas fa-external-link-alt pl-2"></i>
<strong>View full example on GitHub</strong>
</a>
</div>
该库所支持的Python版本最低版本可以在
支持的Python版本
章节中找到 PyPi
这里提供了几种不同的方式来安装 Selenium .
Pip 下载 此外你可以从这里下载 PyPI Built Distribution
(selenium-x.x.x.-py3-none-any.whl) 并通过: pip 文件安装:
pip install selenium-x.x.x.-py3-none-any.whl
在项目中使用 为了在项目中使用它,需要将它添加到 requirements.txt
文件中:
<details class="mt-3">
<summary>Show full example</summary>
<div class="pt-2">
<div class="highlight"><pre tabindex="0" style="background-color:#f8f8f8;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-txt" data-lang="txt"><span style="display:flex;"><span>selenium==4.31.0
pytest==8.3.5
trio==0.29.0
pytest-trio==0.8.0
pytest-rerunfailures==15.0
flake8==7.2.0
requests==2.32.3
<div class="text-end pb-2 mt-2">
<a href="https://github.com/SeleniumHQ/seleniumhq.github.io/blob/display_full/examples/python/requirements.txt#L1" target="_blank">
<i class="fas fa-external-link-alt pl-2"></i>
<strong>View full example on GitHub</strong>
</a>
</div>
Selenium 所支持的所有平台的列表一览
见诸于 Nuget
该处阐述了一些安装Selenium的选项.
包管理器 Install-Package Selenium.WebDriver
.NET CLI dotnet add package Selenium.WebDriver
CSProj 在 csproj
文件里, 具体的依赖 PackageReference
(包参数) 位于 ItemGroup
(项目组)中:
<details class="mt-3">
<summary>Show full example</summary>
<div class="pt-2">
<div class="highlight"><pre tabindex="0" style="background-color:#f8f8f8;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-csproj" data-lang="csproj"><span style="display:flex;"><span><span style="color:#204a87;font-weight:bold"><Project</span> <span style="color:#c4a000">Sdk=</span><span style="color:#4e9a06">"Microsoft.NET.Sdk"</span><span style="color:#204a87;font-weight:bold">></span>
<PropertyGroup>
<TargetFramework> net8.0</TargetFramework>
<GenerateProgramFile> false</GenerateProgramFile>
</PropertyGroup>
<ItemGroup>
<PackageReference Include= "Microsoft.NET.Test.Sdk" Version= "17.11.1" />
<PackageReference Include= "Microsoft.IdentityModel.Tokens" Version= "7.7.1" />
<PackageReference Include= "MSTest.TestAdapter" Version= "3.6.0" />
<PackageReference Include= "MSTest.TestFramework" Version= "3.6.0" />
<PackageReference Include= "Selenium.Support" Version= "4.31.0" />
<PackageReference Include= "Selenium.WebDriver" Version= "4.31.0" />
</ItemGroup>
<ItemGroup>
<Folder Include= "LocalPackages" />
</ItemGroup>
</Project>
<div class="text-end pb-2 mt-2">
<a href="https://github.com/SeleniumHQ/seleniumhq.github.io/blob/display_full/examples/dotnet/SeleniumDocs/SeleniumDocs.csproj#L14" target="_blank">
<i class="fas fa-external-link-alt pl-2"></i>
<strong>View full example on GitHub</strong>
</a>
</div>
其他附加思虑事项 更多的注意事项,适用于使用 Visual Studio Code (vscode) 和 C#
安装兼容的 .NET SDK 作为章节的先决条件
同时安装 vscode 的扩展 (Ctrl-Shift-X)以适配 C# 和 NuGet
可以遵照此处进行 操作指南
创建 C# 控制台项目并运行 “Hello World”.
你也可以用命令行 dotnet new NUnit
创建NUnit初阶项目.
确保文件 %appdata%\NuGet\nuget.config
已经配置完成,就像某位开发者报告的问题一样,它可能因为某种因素被自动清空.
如果 nuget.config
是空的,或者未配置的,那么 .NET 创建的Selenium项目可能失败.
加入如下章节到文件 nuget.config
如果出现清空的情况:
<configuration>
<packageSources>
<add key="nuget.org" value="https://api.nuget.org/v3/index.json" protocolVersion="3" />
<add key="nuget.org" value="https://www.nuget.org/api/v2/" />
</packageSources>
...
更多关于 nuget.config
的信息 点击 .
你可能需要按照自己的需求配置 nuget.config
.
现在,返回 vscode ,按下 Ctrl-Shift-P, 然后键入 “NuGet Add Package”, 并选择自己需要的 Selenium 包,例如 Selenium.WebDriver
.
按下回车并选择版本.
现在你可以使用说明文档中关于 C# vscode下的案例了.
你可以查看 Selenium 对 Ruby 版本支持和最低支持.
具体位于 rubygems.org
Selenium 可以使用两种不同方法安装.
手动安装 gem install selenium-webdriver
加入项目的 gemfile <details class="mt-3">
<summary>Show full example</summary>
<div class="pt-2">
<div class="highlight"><pre tabindex="0" style="background-color:#f8f8f8;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-Gemfile" data-lang="Gemfile"><span style="display:flex;"><span><span style="color:#8f5902;font-style:italic"># frozen_string_literal: true</span>
source 'https://rubygems.org'
gem 'ffi' , '~> 1.15' , '>= 1.15.5' if Gem . win_platform? # Windows only
gem 'rake' , '~> 13.0'
gem 'rspec' , '~> 3.0'
gem 'rubocop' , '~> 1.35'
gem 'rubocop-rspec' , '~> 3.0'
gem 'selenium-devtools' , '= 0.135.0'
gem 'selenium-webdriver' , '= 4.31.0'
<div class="text-end pb-2 mt-2">
<a href="https://github.com/SeleniumHQ/seleniumhq.github.io/blob/display_full/examples/ruby/Gemfile#L10" target="_blank">
<i class="fas fa-external-link-alt pl-2"></i>
<strong>View full example on GitHub</strong>
</a>
</div>
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
:
<details class="mt-3">
<summary>Show full example</summary>
<div class="pt-2">
<div class="highlight"><pre tabindex="0" style="background-color:#f8f8f8;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-json" data-lang="json"><span style="display:flex;"><span><span style="color:#000;font-weight:bold">{</span>
"name" : "javascript-examples" ,
"version" : "1.0.0" ,
"scripts" : {
"test" : "npx mocha test/**/*.spec.js –timeout 90000"
},
"author" : "The Selenium project" ,
"license" : "Apache-2.0" ,
"dependencies" : {
"assert" : "2.1.0" ,
"selenium-webdriver" : "4.31.0"
},
"devDependencies" : {
"mocha" : "11.1.0"
}
}
<div class="text-end pb-2 mt-2">
<a href="https://github.com/SeleniumHQ/seleniumhq.github.io/blob/display_full/examples/javascript/package.json#L14" target="_blank">
<i class="fas fa-external-link-alt pl-2"></i>
<strong>View full example on GitHub</strong>
</a>
</div>
Use the Java bindings for Kotlin.
下一步 创建你的第一个Selenium脚本
2 - 编写第一个Selenium脚本 逐步构建一个Selenium脚本的说明
当你完成 Selenium安装 后, 便可以开始书写Selenium脚本了.
八个基本组成部分 Selenium所做的一切,
就是发送给浏览器命令,
用以执行某些操作或为信息发送请求.
您将使用Selenium执行的大部分操作,
都是以下基本命令的组合
点击 “View full example on GitHub” 的链接以查看上下文中的代码.
1. 使用驱动实例开启会话 关于如何启动会话,请浏览我们的文档 驱动会话
Java
Python
CSharp
Ruby
JavaScript
Kotlin Show full example package dev.selenium.getting_started ;
import org.openqa.selenium.By ;
import org.openqa.selenium.WebDriver ;
import org.openqa.selenium.WebElement ;
import org.openqa.selenium.chrome.ChromeDriver ;
import java.time.Duration ;
public class FirstScript {
public static void main ( String [] args ) {
WebDriver driver = new ChromeDriver ();
driver . get ( "https://www.selenium.dev/selenium/web/web-form.html" );
driver . getTitle ();
driver . manage (). timeouts (). implicitlyWait ( Duration . ofMillis ( 500 ));
WebElement textBox = driver . findElement ( By . name ( "my-text" ));
WebElement submitButton = driver . findElement ( By . cssSelector ( "button" ));
textBox . sendKeys ( "Selenium" );
submitButton . click ();
WebElement message = driver . findElement ( By . id ( "message" ));
message . getText ();
driver . quit ();
}
}
Show full example from selenium import webdriver
from selenium.webdriver.common.by import By
driver = webdriver . Chrome ()
driver . get ( "https://www.selenium.dev/selenium/web/web-form.html" )
title = driver . title
driver . implicitly_wait ( 0.5 )
text_box = driver . find_element ( by = By . NAME , value = "my-text" )
submit_button = driver . find_element ( by = By . CSS_SELECTOR , value = "button" )
text_box . send_keys ( "Selenium" )
submit_button . click ()
message = driver . find_element ( by = By . ID , value = "message" )
text = message . text
driver . quit ()
Show full example using System ;
using OpenQA.Selenium ;
using OpenQA.Selenium.Chrome ;
namespace SeleniumDocs.GettingStarted ;
public static class FirstScript
{
public static void Main ()
{
IWebDriver driver = new ChromeDriver ();
driver . Navigate (). GoToUrl ( "https://www.selenium.dev/selenium/web/web-form.html" );
var title = driver . Title ;
driver . Manage (). Timeouts (). ImplicitWait = TimeSpan . FromMilliseconds ( 500 );
var textBox = driver . FindElement ( By . Name ( "my-text" ));
var submitButton = driver . FindElement ( By . TagName ( "button" ));
textBox . SendKeys ( "Selenium" );
submitButton . Click ();
var message = driver . FindElement ( By . Id ( "message" ));
var value = message . Text ;
driver . Quit ();
}
}
Show full example require 'selenium-webdriver'
driver = Selenium :: WebDriver . for :chrome
driver . get ( 'https://www.selenium.dev/selenium/web/web-form.html' )
driver . title
driver . manage . timeouts . implicit_wait = 500
text_box = driver . find_element ( name : 'my-text' )
submit_button = driver . find_element ( tag_name : 'button' )
text_box . send_keys ( 'Selenium' )
submit_button . click
message = driver . find_element ( id : 'message' )
message . text
driver . quit
Show full example const { By , Builder , Browser } = require ( 'selenium-webdriver' );
const assert = require ( "assert" );
( async function firstTest () {
let driver ;
try {
driver = await new Builder (). forBrowser ( Browser . CHROME ). build ();
await driver . get ( 'https://www.selenium.dev/selenium/web/web-form.html' );
let title = await driver . getTitle ();
assert . equal ( "Web form" , title );
await driver . manage (). setTimeouts ({ implicit : 500 });
let textBox = await driver . findElement ( By . name ( 'my-text' ));
let submitButton = await driver . findElement ( By . css ( 'button' ));
await textBox . sendKeys ( 'Selenium' );
await submitButton . click ();
let message = await driver . findElement ( By . id ( 'message' ));
let value = await message . getText ();
assert . equal ( "Received!" , value );
} catch ( e ) {
console . log ( e )
} finally {
await driver . quit ();
}
}())
Show full example package dev.selenium.getting_started
import org.junit.jupiter.api.*
import org.junit.jupiter.api.Assertions.assertEquals
import org.openqa.selenium.By
import org.openqa.selenium.WebDriver
import org.openqa.selenium.chrome.ChromeDriver
import java.time.Duration
@TestInstance ( TestInstance . Lifecycle . PER_CLASS )
class FirstScriptTest {
private lateinit var driver : WebDriver
@Test
fun eightComponents () {
driver = ChromeDriver ()
driver . get ( "https://www.selenium.dev/selenium/web/web-form.html" )
val title = driver . title
assertEquals ( "Web form" , title )
driver . manage (). timeouts (). implicitlyWait ( Duration . ofMillis ( 500 ))
var textBox = driver . findElement ( By . name ( "my-text" ))
val submitButton = driver . findElement ( By . cssSelector ( "button" ))
textBox . sendKeys ( "Selenium" )
submitButton . click ()
val message = driver . findElement ( By . id ( "message" ))
val value = message . getText ()
assertEquals ( "Received!" , value )
driver . quit ()
}
}
2. 在浏览器上执行操作 在本例中, 我们
导航
到一个网页.
Java
Python
CSharp
Ruby
JavaScript
Kotlin Show full example package dev.selenium.getting_started ;
import org.openqa.selenium.By ;
import org.openqa.selenium.WebDriver ;
import org.openqa.selenium.WebElement ;
import org.openqa.selenium.chrome.ChromeDriver ;
import java.time.Duration ;
public class FirstScript {
public static void main ( String [] args ) {
WebDriver driver = new ChromeDriver ();
driver . get ( "https://www.selenium.dev/selenium/web/web-form.html" );
driver . getTitle ();
driver . manage (). timeouts (). implicitlyWait ( Duration . ofMillis ( 500 ));
WebElement textBox = driver . findElement ( By . name ( "my-text" ));
WebElement submitButton = driver . findElement ( By . cssSelector ( "button" ));
textBox . sendKeys ( "Selenium" );
submitButton . click ();
WebElement message = driver . findElement ( By . id ( "message" ));
message . getText ();
driver . quit ();
}
}
Show full example from selenium import webdriver
from selenium.webdriver.common.by import By
driver = webdriver . Chrome ()
driver . get ( "https://www.selenium.dev/selenium/web/web-form.html" )
title = driver . title
driver . implicitly_wait ( 0.5 )
text_box = driver . find_element ( by = By . NAME , value = "my-text" )
submit_button = driver . find_element ( by = By . CSS_SELECTOR , value = "button" )
text_box . send_keys ( "Selenium" )
submit_button . click ()
message = driver . find_element ( by = By . ID , value = "message" )
text = message . text
driver . quit ()
Show full example using System ;
using OpenQA.Selenium ;
using OpenQA.Selenium.Chrome ;
namespace SeleniumDocs.GettingStarted ;
public static class FirstScript
{
public static void Main ()
{
IWebDriver driver = new ChromeDriver ();
driver . Navigate (). GoToUrl ( "https://www.selenium.dev/selenium/web/web-form.html" );
var title = driver . Title ;
driver . Manage (). Timeouts (). ImplicitWait = TimeSpan . FromMilliseconds ( 500 );
var textBox = driver . FindElement ( By . Name ( "my-text" ));
var submitButton = driver . FindElement ( By . TagName ( "button" ));
textBox . SendKeys ( "Selenium" );
submitButton . Click ();
var message = driver . FindElement ( By . Id ( "message" ));
var value = message . Text ;
driver . Quit ();
}
}
Show full example require 'selenium-webdriver'
driver = Selenium :: WebDriver . for :chrome
driver . get ( 'https://www.selenium.dev/selenium/web/web-form.html' )
driver . title
driver . manage . timeouts . implicit_wait = 500
text_box = driver . find_element ( name : 'my-text' )
submit_button = driver . find_element ( tag_name : 'button' )
text_box . send_keys ( 'Selenium' )
submit_button . click
message = driver . find_element ( id : 'message' )
message . text
driver . quit
Show full example const { By , Builder , Browser } = require ( 'selenium-webdriver' );
const assert = require ( "assert" );
( async function firstTest () {
let driver ;
try {
driver = await new Builder (). forBrowser ( Browser . CHROME ). build ();
await driver . get ( 'https://www.selenium.dev/selenium/web/web-form.html' );
let title = await driver . getTitle ();
assert . equal ( "Web form" , title );
await driver . manage (). setTimeouts ({ implicit : 500 });
let textBox = await driver . findElement ( By . name ( 'my-text' ));
let submitButton = await driver . findElement ( By . css ( 'button' ));
await textBox . sendKeys ( 'Selenium' );
await submitButton . click ();
let message = await driver . findElement ( By . id ( 'message' ));
let value = await message . getText ();
assert . equal ( "Received!" , value );
} catch ( e ) {
console . log ( e )
} finally {
await driver . quit ();
}
}())
Show full example package dev.selenium.getting_started
import org.junit.jupiter.api.*
import org.junit.jupiter.api.Assertions.assertEquals
import org.openqa.selenium.By
import org.openqa.selenium.WebDriver
import org.openqa.selenium.chrome.ChromeDriver
import java.time.Duration
@TestInstance ( TestInstance . Lifecycle . PER_CLASS )
class FirstScriptTest {
private lateinit var driver : WebDriver
@Test
fun eightComponents () {
driver = ChromeDriver ()
driver . get ( "https://www.selenium.dev/selenium/web/web-form.html" )
val title = driver . title
assertEquals ( "Web form" , title )
driver . manage (). timeouts (). implicitlyWait ( Duration . ofMillis ( 500 ))
var textBox = driver . findElement ( By . name ( "my-text" ))
val submitButton = driver . findElement ( By . cssSelector ( "button" ))
textBox . sendKeys ( "Selenium" )
submitButton . click ()
val message = driver . findElement ( By . id ( "message" ))
val value = message . getText ()
assertEquals ( "Received!" , value )
driver . quit ()
}
}
您可以请求一系列关于浏览器的信息 ,
包括窗口句柄、浏览器尺寸/位置、cookie、警报等.
Java
Python
CSharp
Ruby
JavaScript
Kotlin Show full example package dev.selenium.getting_started ;
import org.openqa.selenium.By ;
import org.openqa.selenium.WebDriver ;
import org.openqa.selenium.WebElement ;
import org.openqa.selenium.chrome.ChromeDriver ;
import java.time.Duration ;
public class FirstScript {
public static void main ( String [] args ) {
WebDriver driver = new ChromeDriver ();
driver . get ( "https://www.selenium.dev/selenium/web/web-form.html" );
driver . getTitle ();
driver . manage (). timeouts (). implicitlyWait ( Duration . ofMillis ( 500 ));
WebElement textBox = driver . findElement ( By . name ( "my-text" ));
WebElement submitButton = driver . findElement ( By . cssSelector ( "button" ));
textBox . sendKeys ( "Selenium" );
submitButton . click ();
WebElement message = driver . findElement ( By . id ( "message" ));
message . getText ();
driver . quit ();
}
}
Show full example from selenium import webdriver
from selenium.webdriver.common.by import By
driver = webdriver . Chrome ()
driver . get ( "https://www.selenium.dev/selenium/web/web-form.html" )
title = driver . title
driver . implicitly_wait ( 0.5 )
text_box = driver . find_element ( by = By . NAME , value = "my-text" )
submit_button = driver . find_element ( by = By . CSS_SELECTOR , value = "button" )
text_box . send_keys ( "Selenium" )
submit_button . click ()
message = driver . find_element ( by = By . ID , value = "message" )
text = message . text
driver . quit ()
Show full example using System ;
using OpenQA.Selenium ;
using OpenQA.Selenium.Chrome ;
namespace SeleniumDocs.GettingStarted ;
public static class FirstScript
{
public static void Main ()
{
IWebDriver driver = new ChromeDriver ();
driver . Navigate (). GoToUrl ( "https://www.selenium.dev/selenium/web/web-form.html" );
var title = driver . Title ;
driver . Manage (). Timeouts (). ImplicitWait = TimeSpan . FromMilliseconds ( 500 );
var textBox = driver . FindElement ( By . Name ( "my-text" ));
var submitButton = driver . FindElement ( By . TagName ( "button" ));
textBox . SendKeys ( "Selenium" );
submitButton . Click ();
var message = driver . FindElement ( By . Id ( "message" ));
var value = message . Text ;
driver . Quit ();
}
}
Show full example require 'selenium-webdriver'
driver = Selenium :: WebDriver . for :chrome
driver . get ( 'https://www.selenium.dev/selenium/web/web-form.html' )
driver . title
driver . manage . timeouts . implicit_wait = 500
text_box = driver . find_element ( name : 'my-text' )
submit_button = driver . find_element ( tag_name : 'button' )
text_box . send_keys ( 'Selenium' )
submit_button . click
message = driver . find_element ( id : 'message' )
message . text
driver . quit
Show full example const { By , Builder , Browser } = require ( 'selenium-webdriver' );
const assert = require ( "assert" );
( async function firstTest () {
let driver ;
try {
driver = await new Builder (). forBrowser ( Browser . CHROME ). build ();
await driver . get ( 'https://www.selenium.dev/selenium/web/web-form.html' );
let title = await driver . getTitle ();
assert . equal ( "Web form" , title );
await driver . manage (). setTimeouts ({ implicit : 500 });
let textBox = await driver . findElement ( By . name ( 'my-text' ));
let submitButton = await driver . findElement ( By . css ( 'button' ));
await textBox . sendKeys ( 'Selenium' );
await submitButton . click ();
let message = await driver . findElement ( By . id ( 'message' ));
let value = await message . getText ();
assert . equal ( "Received!" , value );
} catch ( e ) {
console . log ( e )
} finally {
await driver . quit ();
}
}())
Show full example package dev.selenium.getting_started
import org.junit.jupiter.api.*
import org.junit.jupiter.api.Assertions.assertEquals
import org.openqa.selenium.By
import org.openqa.selenium.WebDriver
import org.openqa.selenium.chrome.ChromeDriver
import java.time.Duration
@TestInstance ( TestInstance . Lifecycle . PER_CLASS )
class FirstScriptTest {
private lateinit var driver : WebDriver
@Test
fun eightComponents () {
driver = ChromeDriver ()
driver . get ( "https://www.selenium.dev/selenium/web/web-form.html" )
val title = driver . title
assertEquals ( "Web form" , title )
driver . manage (). timeouts (). implicitlyWait ( Duration . ofMillis ( 500 ))
var textBox = driver . findElement ( By . name ( "my-text" ))
val submitButton = driver . findElement ( By . cssSelector ( "button" ))
textBox . sendKeys ( "Selenium" )
submitButton . click ()
val message = driver . findElement ( By . id ( "message" ))
val value = message . getText ()
assertEquals ( "Received!" , value )
driver . quit ()
}
}
4. 建立等待策略 将代码与浏览器的当前状态同步
是Selenium面临的最大挑战之一,
做好它是一个高级主题.
基本上, 您希望在尝试定位元素之前,
确保该元素位于页面上,
并且在尝试与该元素交互之前,
该元素处于可交互状态.
隐式等待很少是最好的解决方案,
但在这里最容易演示,
所以我们将使用它作为占位符.
阅读更多关于等待策略
的信息.
Java
Python
CSharp
Ruby
JavaScript
Kotlin Show full example package dev.selenium.getting_started ;
import org.openqa.selenium.By ;
import org.openqa.selenium.WebDriver ;
import org.openqa.selenium.WebElement ;
import org.openqa.selenium.chrome.ChromeDriver ;
import java.time.Duration ;
public class FirstScript {
public static void main ( String [] args ) {
WebDriver driver = new ChromeDriver ();
driver . get ( "https://www.selenium.dev/selenium/web/web-form.html" );
driver . getTitle ();
driver . manage (). timeouts (). implicitlyWait ( Duration . ofMillis ( 500 ));
WebElement textBox = driver . findElement ( By . name ( "my-text" ));
WebElement submitButton = driver . findElement ( By . cssSelector ( "button" ));
textBox . sendKeys ( "Selenium" );
submitButton . click ();
WebElement message = driver . findElement ( By . id ( "message" ));
message . getText ();
driver . quit ();
}
}
Show full example from selenium import webdriver
from selenium.webdriver.common.by import By
driver = webdriver . Chrome ()
driver . get ( "https://www.selenium.dev/selenium/web/web-form.html" )
title = driver . title
driver . implicitly_wait ( 0.5 )
text_box = driver . find_element ( by = By . NAME , value = "my-text" )
submit_button = driver . find_element ( by = By . CSS_SELECTOR , value = "button" )
text_box . send_keys ( "Selenium" )
submit_button . click ()
message = driver . find_element ( by = By . ID , value = "message" )
text = message . text
driver . quit ()
Show full example using System ;
using OpenQA.Selenium ;
using OpenQA.Selenium.Chrome ;
namespace SeleniumDocs.GettingStarted ;
public static class FirstScript
{
public static void Main ()
{
IWebDriver driver = new ChromeDriver ();
driver . Navigate (). GoToUrl ( "https://www.selenium.dev/selenium/web/web-form.html" );
var title = driver . Title ;
driver . Manage (). Timeouts (). ImplicitWait = TimeSpan . FromMilliseconds ( 500 );
var textBox = driver . FindElement ( By . Name ( "my-text" ));
var submitButton = driver . FindElement ( By . TagName ( "button" ));
textBox . SendKeys ( "Selenium" );
submitButton . Click ();
var message = driver . FindElement ( By . Id ( "message" ));
var value = message . Text ;
driver . Quit ();
}
}
Show full example require 'selenium-webdriver'
driver = Selenium :: WebDriver . for :chrome
driver . get ( 'https://www.selenium.dev/selenium/web/web-form.html' )
driver . title
driver . manage . timeouts . implicit_wait = 500
text_box = driver . find_element ( name : 'my-text' )
submit_button = driver . find_element ( tag_name : 'button' )
text_box . send_keys ( 'Selenium' )
submit_button . click
message = driver . find_element ( id : 'message' )
message . text
driver . quit
Show full example const { By , Builder , Browser } = require ( 'selenium-webdriver' );
const assert = require ( "assert" );
( async function firstTest () {
let driver ;
try {
driver = await new Builder (). forBrowser ( Browser . CHROME ). build ();
await driver . get ( 'https://www.selenium.dev/selenium/web/web-form.html' );
let title = await driver . getTitle ();
assert . equal ( "Web form" , title );
await driver . manage (). setTimeouts ({ implicit : 500 });
let textBox = await driver . findElement ( By . name ( 'my-text' ));
let submitButton = await driver . findElement ( By . css ( 'button' ));
await textBox . sendKeys ( 'Selenium' );
await submitButton . click ();
let message = await driver . findElement ( By . id ( 'message' ));
let value = await message . getText ();
assert . equal ( "Received!" , value );
} catch ( e ) {
console . log ( e )
} finally {
await driver . quit ();
}
}())
Show full example package dev.selenium.getting_started
import org.junit.jupiter.api.*
import org.junit.jupiter.api.Assertions.assertEquals
import org.openqa.selenium.By
import org.openqa.selenium.WebDriver
import org.openqa.selenium.chrome.ChromeDriver
import java.time.Duration
@TestInstance ( TestInstance . Lifecycle . PER_CLASS )
class FirstScriptTest {
private lateinit var driver : WebDriver
@Test
fun eightComponents () {
driver = ChromeDriver ()
driver . get ( "https://www.selenium.dev/selenium/web/web-form.html" )
val title = driver . title
assertEquals ( "Web form" , title )
driver . manage (). timeouts (). implicitlyWait ( Duration . ofMillis ( 500 ))
var textBox = driver . findElement ( By . name ( "my-text" ))
val submitButton = driver . findElement ( By . cssSelector ( "button" ))
textBox . sendKeys ( "Selenium" )
submitButton . click ()
val message = driver . findElement ( By . id ( "message" ))
val value = message . getText ()
assertEquals ( "Received!" , value )
driver . quit ()
}
}
大多数Selenium会话中的主要命令都与元素相关,
如果不先找到元素 ,
就无法与之交互.
Java
Python
CSharp
Ruby
JavaScript
Kotlin Show full example package dev.selenium.getting_started ;
import org.openqa.selenium.By ;
import org.openqa.selenium.WebDriver ;
import org.openqa.selenium.WebElement ;
import org.openqa.selenium.chrome.ChromeDriver ;
import java.time.Duration ;
public class FirstScript {
public static void main ( String [] args ) {
WebDriver driver = new ChromeDriver ();
driver . get ( "https://www.selenium.dev/selenium/web/web-form.html" );
driver . getTitle ();
driver . manage (). timeouts (). implicitlyWait ( Duration . ofMillis ( 500 ));
WebElement textBox = driver . findElement ( By . name ( "my-text" ));
WebElement submitButton = driver . findElement ( By . cssSelector ( "button" ));
textBox . sendKeys ( "Selenium" );
submitButton . click ();
WebElement message = driver . findElement ( By . id ( "message" ));
message . getText ();
driver . quit ();
}
}
Show full example from selenium import webdriver
from selenium.webdriver.common.by import By
driver = webdriver . Chrome ()
driver . get ( "https://www.selenium.dev/selenium/web/web-form.html" )
title = driver . title
driver . implicitly_wait ( 0.5 )
text_box = driver . find_element ( by = By . NAME , value = "my-text" )
submit_button = driver . find_element ( by = By . CSS_SELECTOR , value = "button" )
text_box . send_keys ( "Selenium" )
submit_button . click ()
message = driver . find_element ( by = By . ID , value = "message" )
text = message . text
driver . quit ()
Show full example using System ;
using OpenQA.Selenium ;
using OpenQA.Selenium.Chrome ;
namespace SeleniumDocs.GettingStarted ;
public static class FirstScript
{
public static void Main ()
{
IWebDriver driver = new ChromeDriver ();
driver . Navigate (). GoToUrl ( "https://www.selenium.dev/selenium/web/web-form.html" );
var title = driver . Title ;
driver . Manage (). Timeouts (). ImplicitWait = TimeSpan . FromMilliseconds ( 500 );
var textBox = driver . FindElement ( By . Name ( "my-text" ));
var submitButton = driver . FindElement ( By . TagName ( "button" ));
textBox . SendKeys ( "Selenium" );
submitButton . Click ();
var message = driver . FindElement ( By . Id ( "message" ));
var value = message . Text ;
driver . Quit ();
}
}
Show full example require 'selenium-webdriver'
driver = Selenium :: WebDriver . for :chrome
driver . get ( 'https://www.selenium.dev/selenium/web/web-form.html' )
driver . title
driver . manage . timeouts . implicit_wait = 500
text_box = driver . find_element ( name : 'my-text' )
submit_button = driver . find_element ( tag_name : 'button' )
text_box . send_keys ( 'Selenium' )
submit_button . click
message = driver . find_element ( id : 'message' )
message . text
driver . quit
Show full example const { By , Builder , Browser } = require ( 'selenium-webdriver' );
const assert = require ( "assert" );
( async function firstTest () {
let driver ;
try {
driver = await new Builder (). forBrowser ( Browser . CHROME ). build ();
await driver . get ( 'https://www.selenium.dev/selenium/web/web-form.html' );
let title = await driver . getTitle ();
assert . equal ( "Web form" , title );
await driver . manage (). setTimeouts ({ implicit : 500 });
let textBox = await driver . findElement ( By . name ( 'my-text' ));
let submitButton = await driver . findElement ( By . css ( 'button' ));
await textBox . sendKeys ( 'Selenium' );
await submitButton . click ();
let message = await driver . findElement ( By . id ( 'message' ));
let value = await message . getText ();
assert . equal ( "Received!" , value );
} catch ( e ) {
console . log ( e )
} finally {
await driver . quit ();
}
}())
Show full example package dev.selenium.getting_started
import org.junit.jupiter.api.*
import org.junit.jupiter.api.Assertions.assertEquals
import org.openqa.selenium.By
import org.openqa.selenium.WebDriver
import org.openqa.selenium.chrome.ChromeDriver
import java.time.Duration
@TestInstance ( TestInstance . Lifecycle . PER_CLASS )
class FirstScriptTest {
private lateinit var driver : WebDriver
@Test
fun eightComponents () {
driver = ChromeDriver ()
driver . get ( "https://www.selenium.dev/selenium/web/web-form.html" )
val title = driver . title
assertEquals ( "Web form" , title )
driver . manage (). timeouts (). implicitlyWait ( Duration . ofMillis ( 500 ))
var textBox = driver . findElement ( By . name ( "my-text" ))
val submitButton = driver . findElement ( By . cssSelector ( "button" ))
textBox . sendKeys ( "Selenium" )
submitButton . click ()
val message = driver . findElement ( By . id ( "message" ))
val value = message . getText ()
assertEquals ( "Received!" , value )
driver . quit ()
}
}
6. 操作元素 对于一个元素,
只有少数几个操作 可以执行,
但您将经常使用它们.
Java
Python
CSharp
Ruby
JavaScript
Kotlin Show full example package dev.selenium.getting_started ;
import org.openqa.selenium.By ;
import org.openqa.selenium.WebDriver ;
import org.openqa.selenium.WebElement ;
import org.openqa.selenium.chrome.ChromeDriver ;
import java.time.Duration ;
public class FirstScript {
public static void main ( String [] args ) {
WebDriver driver = new ChromeDriver ();
driver . get ( "https://www.selenium.dev/selenium/web/web-form.html" );
driver . getTitle ();
driver . manage (). timeouts (). implicitlyWait ( Duration . ofMillis ( 500 ));
WebElement textBox = driver . findElement ( By . name ( "my-text" ));
WebElement submitButton = driver . findElement ( By . cssSelector ( "button" ));
textBox . sendKeys ( "Selenium" );
submitButton . click ();
WebElement message = driver . findElement ( By . id ( "message" ));
message . getText ();
driver . quit ();
}
}
Show full example from selenium import webdriver
from selenium.webdriver.common.by import By
driver = webdriver . Chrome ()
driver . get ( "https://www.selenium.dev/selenium/web/web-form.html" )
title = driver . title
driver . implicitly_wait ( 0.5 )
text_box = driver . find_element ( by = By . NAME , value = "my-text" )
submit_button = driver . find_element ( by = By . CSS_SELECTOR , value = "button" )
text_box . send_keys ( "Selenium" )
submit_button . click ()
message = driver . find_element ( by = By . ID , value = "message" )
text = message . text
driver . quit ()
Show full example using System ;
using OpenQA.Selenium ;
using OpenQA.Selenium.Chrome ;
namespace SeleniumDocs.GettingStarted ;
public static class FirstScript
{
public static void Main ()
{
IWebDriver driver = new ChromeDriver ();
driver . Navigate (). GoToUrl ( "https://www.selenium.dev/selenium/web/web-form.html" );
var title = driver . Title ;
driver . Manage (). Timeouts (). ImplicitWait = TimeSpan . FromMilliseconds ( 500 );
var textBox = driver . FindElement ( By . Name ( "my-text" ));
var submitButton = driver . FindElement ( By . TagName ( "button" ));
textBox . SendKeys ( "Selenium" );
submitButton . Click ();
var message = driver . FindElement ( By . Id ( "message" ));
var value = message . Text ;
driver . Quit ();
}
}
Show full example require 'selenium-webdriver'
driver = Selenium :: WebDriver . for :chrome
driver . get ( 'https://www.selenium.dev/selenium/web/web-form.html' )
driver . title
driver . manage . timeouts . implicit_wait = 500
text_box = driver . find_element ( name : 'my-text' )
submit_button = driver . find_element ( tag_name : 'button' )
text_box . send_keys ( 'Selenium' )
submit_button . click
message = driver . find_element ( id : 'message' )
message . text
driver . quit
Show full example const { By , Builder , Browser } = require ( 'selenium-webdriver' );
const assert = require ( "assert" );
( async function firstTest () {
let driver ;
try {
driver = await new Builder (). forBrowser ( Browser . CHROME ). build ();
await driver . get ( 'https://www.selenium.dev/selenium/web/web-form.html' );
let title = await driver . getTitle ();
assert . equal ( "Web form" , title );
await driver . manage (). setTimeouts ({ implicit : 500 });
let textBox = await driver . findElement ( By . name ( 'my-text' ));
let submitButton = await driver . findElement ( By . css ( 'button' ));
await textBox . sendKeys ( 'Selenium' );
await submitButton . click ();
let message = await driver . findElement ( By . id ( 'message' ));
let value = await message . getText ();
assert . equal ( "Received!" , value );
} catch ( e ) {
console . log ( e )
} finally {
await driver . quit ();
}
}())
Show full example package dev.selenium.getting_started
import org.junit.jupiter.api.*
import org.junit.jupiter.api.Assertions.assertEquals
import org.openqa.selenium.By
import org.openqa.selenium.WebDriver
import org.openqa.selenium.chrome.ChromeDriver
import java.time.Duration
@TestInstance ( TestInstance . Lifecycle . PER_CLASS )
class FirstScriptTest {
private lateinit var driver : WebDriver
@Test
fun eightComponents () {
driver = ChromeDriver ()
driver . get ( "https://www.selenium.dev/selenium/web/web-form.html" )
val title = driver . title
assertEquals ( "Web form" , title )
driver . manage (). timeouts (). implicitlyWait ( Duration . ofMillis ( 500 ))
var textBox = driver . findElement ( By . name ( "my-text" ))
val submitButton = driver . findElement ( By . cssSelector ( "button" ))
textBox . sendKeys ( "Selenium" )
submitButton . click ()
val message = driver . findElement ( By . id ( "message" ))
val value = message . getText ()
assertEquals ( "Received!" , value )
driver . quit ()
}
}
7. 获取元素信息 元素存储了很多被请求的信息 .
Java
Python
CSharp
Ruby
JavaScript
Kotlin Show full example package dev.selenium.getting_started ;
import org.openqa.selenium.By ;
import org.openqa.selenium.WebDriver ;
import org.openqa.selenium.WebElement ;
import org.openqa.selenium.chrome.ChromeDriver ;
import java.time.Duration ;
public class FirstScript {
public static void main ( String [] args ) {
WebDriver driver = new ChromeDriver ();
driver . get ( "https://www.selenium.dev/selenium/web/web-form.html" );
driver . getTitle ();
driver . manage (). timeouts (). implicitlyWait ( Duration . ofMillis ( 500 ));
WebElement textBox = driver . findElement ( By . name ( "my-text" ));
WebElement submitButton = driver . findElement ( By . cssSelector ( "button" ));
textBox . sendKeys ( "Selenium" );
submitButton . click ();
WebElement message = driver . findElement ( By . id ( "message" ));
message . getText ();
driver . quit ();
}
}
Show full example from selenium import webdriver
from selenium.webdriver.common.by import By
driver = webdriver . Chrome ()
driver . get ( "https://www.selenium.dev/selenium/web/web-form.html" )
title = driver . title
driver . implicitly_wait ( 0.5 )
text_box = driver . find_element ( by = By . NAME , value = "my-text" )
submit_button = driver . find_element ( by = By . CSS_SELECTOR , value = "button" )
text_box . send_keys ( "Selenium" )
submit_button . click ()
message = driver . find_element ( by = By . ID , value = "message" )
text = message . text
driver . quit ()
Show full example using System ;
using OpenQA.Selenium ;
using OpenQA.Selenium.Chrome ;
namespace SeleniumDocs.GettingStarted ;
public static class FirstScript
{
public static void Main ()
{
IWebDriver driver = new ChromeDriver ();
driver . Navigate (). GoToUrl ( "https://www.selenium.dev/selenium/web/web-form.html" );
var title = driver . Title ;
driver . Manage (). Timeouts (). ImplicitWait = TimeSpan . FromMilliseconds ( 500 );
var textBox = driver . FindElement ( By . Name ( "my-text" ));
var submitButton = driver . FindElement ( By . TagName ( "button" ));
textBox . SendKeys ( "Selenium" );
submitButton . Click ();
var message = driver . FindElement ( By . Id ( "message" ));
var value = message . Text ;
driver . Quit ();
}
}
Show full example require 'selenium-webdriver'
driver = Selenium :: WebDriver . for :chrome
driver . get ( 'https://www.selenium.dev/selenium/web/web-form.html' )
driver . title
driver . manage . timeouts . implicit_wait = 500
text_box = driver . find_element ( name : 'my-text' )
submit_button = driver . find_element ( tag_name : 'button' )
text_box . send_keys ( 'Selenium' )
submit_button . click
message = driver . find_element ( id : 'message' )
message . text
driver . quit
Show full example const { By , Builder , Browser } = require ( 'selenium-webdriver' );
const assert = require ( "assert" );
( async function firstTest () {
let driver ;
try {
driver = await new Builder (). forBrowser ( Browser . CHROME ). build ();
await driver . get ( 'https://www.selenium.dev/selenium/web/web-form.html' );
let title = await driver . getTitle ();
assert . equal ( "Web form" , title );
await driver . manage (). setTimeouts ({ implicit : 500 });
let textBox = await driver . findElement ( By . name ( 'my-text' ));
let submitButton = await driver . findElement ( By . css ( 'button' ));
await textBox . sendKeys ( 'Selenium' );
await submitButton . click ();
let message = await driver . findElement ( By . id ( 'message' ));
let value = await message . getText ();
assert . equal ( "Received!" , value );
} catch ( e ) {
console . log ( e )
} finally {
await driver . quit ();
}
}())
Show full example package dev.selenium.getting_started
import org.junit.jupiter.api.*
import org.junit.jupiter.api.Assertions.assertEquals
import org.openqa.selenium.By
import org.openqa.selenium.WebDriver
import org.openqa.selenium.chrome.ChromeDriver
import java.time.Duration
@TestInstance ( TestInstance . Lifecycle . PER_CLASS )
class FirstScriptTest {
private lateinit var driver : WebDriver
@Test
fun eightComponents () {
driver = ChromeDriver ()
driver . get ( "https://www.selenium.dev/selenium/web/web-form.html" )
val title = driver . title
assertEquals ( "Web form" , title )
driver . manage (). timeouts (). implicitlyWait ( Duration . ofMillis ( 500 ))
var textBox = driver . findElement ( By . name ( "my-text" ))
val submitButton = driver . findElement ( By . cssSelector ( "button" ))
textBox . sendKeys ( "Selenium" )
submitButton . click ()
val message = driver . findElement ( By . id ( "message" ))
val value = message . getText ()
assertEquals ( "Received!" , value )
driver . quit ()
}
}
8. 结束会话 这将结束驱动程序进程,
默认情况下, 该进程也会关闭浏览器.
无法向此驱动程序实例发送更多命令.
详见 Quitting Sessions .
Java
Python
CSharp
Ruby
JavaScript
Kotlin Show full example package dev.selenium.getting_started ;
import org.openqa.selenium.By ;
import org.openqa.selenium.WebDriver ;
import org.openqa.selenium.WebElement ;
import org.openqa.selenium.chrome.ChromeDriver ;
import java.time.Duration ;
public class FirstScript {
public static void main ( String [] args ) {
WebDriver driver = new ChromeDriver ();
driver . get ( "https://www.selenium.dev/selenium/web/web-form.html" );
driver . getTitle ();
driver . manage (). timeouts (). implicitlyWait ( Duration . ofMillis ( 500 ));
WebElement textBox = driver . findElement ( By . name ( "my-text" ));
WebElement submitButton = driver . findElement ( By . cssSelector ( "button" ));
textBox . sendKeys ( "Selenium" );
submitButton . click ();
WebElement message = driver . findElement ( By . id ( "message" ));
message . getText ();
driver . quit ();
}
}
Show full example from selenium import webdriver
from selenium.webdriver.common.by import By
driver = webdriver . Chrome ()
driver . get ( "https://www.selenium.dev/selenium/web/web-form.html" )
title = driver . title
driver . implicitly_wait ( 0.5 )
text_box = driver . find_element ( by = By . NAME , value = "my-text" )
submit_button = driver . find_element ( by = By . CSS_SELECTOR , value = "button" )
text_box . send_keys ( "Selenium" )
submit_button . click ()
message = driver . find_element ( by = By . ID , value = "message" )
text = message . text
driver . quit ()
Show full example using System ;
using OpenQA.Selenium ;
using OpenQA.Selenium.Chrome ;
namespace SeleniumDocs.GettingStarted ;
public static class FirstScript
{
public static void Main ()
{
IWebDriver driver = new ChromeDriver ();
driver . Navigate (). GoToUrl ( "https://www.selenium.dev/selenium/web/web-form.html" );
var title = driver . Title ;
driver . Manage (). Timeouts (). ImplicitWait = TimeSpan . FromMilliseconds ( 500 );
var textBox = driver . FindElement ( By . Name ( "my-text" ));
var submitButton = driver . FindElement ( By . TagName ( "button" ));
textBox . SendKeys ( "Selenium" );
submitButton . Click ();
var message = driver . FindElement ( By . Id ( "message" ));
var value = message . Text ;
driver . Quit ();
}
}
Show full example require 'selenium-webdriver'
driver = Selenium :: WebDriver . for :chrome
driver . get ( 'https://www.selenium.dev/selenium/web/web-form.html' )
driver . title
driver . manage . timeouts . implicit_wait = 500
text_box = driver . find_element ( name : 'my-text' )
submit_button = driver . find_element ( tag_name : 'button' )
text_box . send_keys ( 'Selenium' )
submit_button . click
message = driver . find_element ( id : 'message' )
message . text
driver . quit
Show full example const { By , Builder , Browser } = require ( 'selenium-webdriver' );
const assert = require ( "assert" );
( async function firstTest () {
let driver ;
try {
driver = await new Builder (). forBrowser ( Browser . CHROME ). build ();
await driver . get ( 'https://www.selenium.dev/selenium/web/web-form.html' );
let title = await driver . getTitle ();
assert . equal ( "Web form" , title );
await driver . manage (). setTimeouts ({ implicit : 500 });
let textBox = await driver . findElement ( By . name ( 'my-text' ));
let submitButton = await driver . findElement ( By . css ( 'button' ));
await textBox . sendKeys ( 'Selenium' );
await submitButton . click ();
let message = await driver . findElement ( By . id ( 'message' ));
let value = await message . getText ();
assert . equal ( "Received!" , value );
} catch ( e ) {
console . log ( e )
} finally {
await driver . quit ();
}
}())
Show full example package dev.selenium.getting_started
import org.junit.jupiter.api.*
import org.junit.jupiter.api.Assertions.assertEquals
import org.openqa.selenium.By
import org.openqa.selenium.WebDriver
import org.openqa.selenium.chrome.ChromeDriver
import java.time.Duration
@TestInstance ( TestInstance . Lifecycle . PER_CLASS )
class FirstScriptTest {
private lateinit var driver : WebDriver
@Test
fun eightComponents () {
driver = ChromeDriver ()
driver . get ( "https://www.selenium.dev/selenium/web/web-form.html" )
val title = driver . title
assertEquals ( "Web form" , title )
driver . manage (). timeouts (). implicitlyWait ( Duration . ofMillis ( 500 ))
var textBox = driver . findElement ( By . name ( "my-text" ))
val submitButton = driver . findElement ( By . cssSelector ( "button" ))
textBox . sendKeys ( "Selenium" )
submitButton . click ()
val message = driver . findElement ( By . id ( "message" ))
val value = message . getText ()
assertEquals ( "Received!" , value )
driver . quit ()
}
}
运行 Selenium 文件
Java
Python
CSharp
Ruby
JavaScript
Kotlin Show full example # Running Selenium Java Tests
The following steps will guide you on how to
run Selenium Java tests using a repository
of `SeleniumHQ/seleniumhq.github.io` examples.
## Initial Setup
### Prerequisites
Ensure that Java Development Kit (JDK) and Maven
are installed on your system. If they are not installed,
you will need to download and install them. You can
find detailed installation guides for both on their
respective official sites.
### Clone the repository
First, we need to get the Selenium Java examples
on your local machine. This can be done by
cloning the `SeleniumHQ/seleniumhq.github.io` Git repository.
Run the following command in your terminal:
```bash
git clone https://github.com/SeleniumHQ/seleniumhq.github.io.git
```
## Navigate to the java directory
After cloning the repository, navigate into the
directory where the Selenium Java examples are
located. Run the following command:
```bash
cd seleniumhq.github.io/examples/java
```
## Running the Tests
### Install dependencies
Before running the tests, we need to install all
necessary dependencies. Maven, a software
project management tool, can do this for us.
Run the following command:
```bash
mvn test-compile
```
### Run all tests
To verify if everything is installed correctly and
functioning properly, we should run all
available tests. This can be done with the following command:
```bash
mvn test
```
Please be patient! If this is your first time running these tests,
it might take a while to download and verify all necessary browser drivers.
## Execute a specific example
To run a specific Selenium Java example, use the following command:
```bash
mvn exec:java -D"exec.mainClass" = "dev.selenium.getting_started.FirstScript" -D"exec.classpathScope" = test
```
Make sure to replace `dev.selenium.getting_started.FirstScript` with the path and name of the example you want to run.
Show full example # Running all tests from Selenium python example
Follow these steps to run all test example from selenium python
1. Clone this repository
```
git clone https://github.com/SeleniumHQ/seleniumhq.github.io.git
```
2. Navigate to `python` directory
```
cd seleniumhq.github.io/examples/python
```
3. Install dependencies using pip
```
pip install -r requirements.txt
```
> if you are on a different python version, for example python3.x you may have to replace `pip` with `pip3`
4. Run all tests
```
pytest
```
> Please keep some patience - If you are doing it for the first time, it will take a little while to verify and download the browser drivers
## Execute a specific example
To run a specific Selenium Python example, use the following command:
```bash
pytest path/to/test_script.py
```
Make sure to replace `path/to/test_script.py` with the path and name of the example you want to run.
Show full example # Running all tests from Selenium ruby example
Follow these steps to run all test example from selenium ruby
1. Clone this repository
```
git clone https://github.com/SeleniumHQ/seleniumhq.github.io.git
```
2. Navigate to `ruby` directory
```
cd seleniumhq.github.io/examples/ruby
```
3. Install dependencies using bundler
```
bundler install
```
4. Run all tests
```
bundle exec rspec
```
> Please keep some patience - If you are doing it for the first time, it will take a little while to verify and download the browser drivers
# Execute a ruby script
Use this command to run a ruby script and follow the first script example
```
ruby example_script.rb
```
Show full example # Running all tests from Selenium javascript example
Follow these steps to run all test example from selenium javascript
1. Clone this repository
```
git clone https://github.com/SeleniumHQ/seleniumhq.github.io.git
```
2. Navigate to `javascript` directory
```
cd seleniumhq.github.io/examples/javascript
```
3. Install dependencies using node
```
npm install
```
4. Run all all tests
```
npm test
```
> Please keep some patience - If you are doing it for the first time, it will take a little while to verify and download the browser drivers
# Execute a javascript test
Use this command to run a JavaScript and follow the first script example
```
node example_script.spec.js
```
接下来的步骤 大多数 Selenium 用户执行许多会话,
需要组织它们以最大限度地减少重复并维持代码更易于维护.
请继续阅读,了解如何将此代码放入您用例的上下文中
使用 Selenium .
3 - 组织和执行Selenium代码 使用IDE和Test Runner库组织Selenium的执行
如果你不仅仅只是想执行一小撮的一次性脚本,你需要能组织和安排好你的代码。这一页会启发你如何真正地使用 Selenium 代码做高效的事情。
常见用法 大部分人使用 Selenium 执行针对 Web 应用的自动化测试,但是 Selenium 其实可以支持任何场景的浏览器自动化。
重复性任务 有时候你需要往网站记录日志或者下载一些东西,或者提交一个表单,你可以在预设的时间创建一个 Selenium 脚本去执行一个服务。
网页爬虫 你是否期望从一个不提供 API 的网站收集数据?Selenium 可以满足你,但是请确保你了解该网站的服务条例,因为有些网站不允许你这样做,甚至有些网站会屏蔽 Selenium。
测试 使用 Selenium 做测试需要在 Selenium 执行操作后进行断言,所以一个好的断言类库是很有必要的。至于组织测试用例结构的一些额外特性则需要Test Runner 来完成。
IDEs 不管你要用 Selenium 来做什么,没有一个好的集成开发环境,你的工作肯定不会高效。以下是一些常见的 IDE 选择:
Test Runner 即使不使用 Selenium 做测试,如果你有高级用例,使用一个 test runner 去更好地组织你的代码是很有意义的。学会使用 before/after hooks 和分组执行或者并行执行将会非常有用。
待选 有非常多不同的 test runner 可供选择。
这个教程中所有使用到 test runner 的代码示例都可以在我们的示例目录中找到(或者正在被迁移过去),而且这些示例在每一次发版都会被执行,以确保代码是正确的和最新的。下面是一份包含对应链接的 test runner 清单,其中第一项是被这个仓库和本页所有用例所使用的。
Java
Python
CSharp
Ruby
JavaScript
Kotlin JUnit - 个广泛使用的用于基于 Java 的 Selenium 测试的测试框架。TestNG - 提供诸如并行测试执行和参数化测试等额外功能。RSpec - Ruby中运行Selenium测试最广泛使用的测试库Minitest - 一个随Ruby标准库附带的轻量级测试框架Jest - 主要作为React的测试框架而闻名,但也可以用于Selenium测试Mocha -最常用的运行Selenium测试的JavaScript库。Kotest - 个灵活且全面的测试框架,专为 Kotlin 设计。JUnit5 -标准的 Java 测试框架,完全兼容 Kotlin。安装 在安装 Selenium 类库 一节中详细说明了需要哪些东西。这里的代码只展示在我们的文档示例项目中用到的示例。
Java
Python
CSharp
Ruby
JavaScript
Kotlin To use it in a project, add it to the requirements.txt
file:
in the project’s csproj
file, specify the dependency as a PackageReference
in ItemGroup
:
In your project’s package.json
, add requirement to dependencies
:
断言
Java
Python
CSharp
Ruby
JavaScript
Kotlin Show full example package dev.selenium.getting_started ;
import static org.junit.jupiter.api.Assertions.assertEquals ;
import java.time.Duration ;
import org.junit.jupiter.api.AfterEach ;
import org.junit.jupiter.api.BeforeEach ;
import org.junit.jupiter.api.Test ;
import org.openqa.selenium.By ;
import org.openqa.selenium.WebDriver ;
import org.openqa.selenium.WebElement ;
import org.openqa.selenium.chrome.ChromeDriver ;
public class UsingSeleniumTest {
WebDriver driver ;
@BeforeEach
public void setup () {
driver = new ChromeDriver ();
}
@Test
public void eightComponents () {
driver . manage (). timeouts (). implicitlyWait ( Duration . ofMillis ( 500 ));
driver . get ( "https://www.selenium.dev/selenium/web/web-form.html" );
String title = driver . getTitle ();
assertEquals ( "Web form" , title );
WebElement textBox = driver . findElement ( By . name ( "my-text" ));
WebElement submitButton = driver . findElement ( By . cssSelector ( "button" ));
textBox . sendKeys ( "Selenium" );
submitButton . click ();
WebElement message = driver . findElement ( By . id ( "message" ));
String value = message . getText ();
assertEquals ( "Received!" , value );
}
@AfterEach
public void teardown () {
driver . quit ();
}
}
<details class="mt-3">
<summary>Show full example</summary>
<div class="pt-2">
<div class="highlight"><pre tabindex="0" style="background-color:#f8f8f8;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-py" data-lang="py"><span style="display:flex;"><span><span style="color:#204a87;font-weight:bold">from</span> <span style="color:#000">selenium</span> <span style="color:#204a87;font-weight:bold">import</span> <span style="color:#000">webdriver</span>
from selenium.webdriver.common.by import By
def test_eight_components ():
driver = setup ()
title = driver . title
assert title == "Web form"
driver . implicitly_wait ( 0.5 )
text_box = driver . find_element ( by = By . NAME , value = "my-text" )
submit_button = driver . find_element ( by = By . CSS_SELECTOR , value = "button" )
text_box . send_keys ( "Selenium" )
submit_button . click ()
message = driver . find_element ( by = By . ID , value = "message" )
value = message . text
assert value == "Received!"
teardown ( driver )
def setup ():
driver = webdriver . Chrome ()
driver . get ( "https://www.selenium.dev/selenium/web/web-form.html" )
return driver
def teardown ( driver ):
driver . quit ()
<div class="text-end pb-2 mt-2">
<a href="https://github.com/SeleniumHQ/seleniumhq.github.io/blob/display_full/examples/python/tests/getting_started/using_selenium_tests.py#L8-L9" target="_blank">
<i class="fas fa-external-link-alt pl-2"></i>
<strong>View full example on GitHub</strong>
</a>
</div>
Show full example using System ;
using Microsoft.VisualStudio.TestTools.UnitTesting ;
using OpenQA.Selenium ;
using OpenQA.Selenium.Chrome ;
namespace SeleniumDocs.GettingStarted
{
[TestClass]
public class UsingSeleniumTest
{
[TestMethod]
public void EightComponents ()
{
IWebDriver driver = new ChromeDriver ();
driver . Navigate (). GoToUrl ( "https://www.selenium.dev/selenium/web/web-form.html" );
var title = driver . Title ;
Assert . AreEqual ( "Web form" , title );
driver . Manage (). Timeouts (). ImplicitWait = TimeSpan . FromMilliseconds ( 500 );
var textBox = driver . FindElement ( By . Name ( "my-text" ));
var submitButton = driver . FindElement ( By . TagName ( "button" ));
textBox . SendKeys ( "Selenium" );
submitButton . Click ();
var message = driver . FindElement ( By . Id ( "message" ));
var value = message . Text ;
Assert . AreEqual ( "Received!" , value );
driver . Quit ();
}
}
}
Show full example # frozen_string_literal: true
require 'selenium-webdriver'
RSpec . describe 'Using Selenium' do
it 'uses eight components' do
driver = Selenium :: WebDriver . for :chrome
driver . get ( 'https://www.selenium.dev/selenium/web/web-form.html' )
title = driver . title
expect ( title ) . to eq ( 'Web form' )
driver . manage . timeouts . implicit_wait = 500
text_box = driver . find_element ( name : 'my-text' )
submit_button = driver . find_element ( tag_name : 'button' )
text_box . send_keys ( 'Selenium' )
submit_button . click
message = driver . find_element ( id : 'message' )
value = message . text
expect ( value ) . to eq ( 'Received!' )
driver . quit
end
end
Show full example const { By , Builder } = require ( 'selenium-webdriver' );
const assert = require ( "assert" );
describe ( 'First script' , function () {
let driver ;
before ( async function () {
driver = await new Builder (). forBrowser ( 'chrome' ). build ();
});
it ( 'First Selenium script with mocha' , async function () {
await driver . get ( 'https://www.selenium.dev/selenium/web/web-form.html' );
let title = await driver . getTitle ();
assert . equal ( "Web form" , title );
await driver . manage (). setTimeouts ({ implicit : 500 });
let textBox = await driver . findElement ( By . name ( 'my-text' ));
let submitButton = await driver . findElement ( By . css ( 'button' ));
await textBox . sendKeys ( 'Selenium' );
await submitButton . click ();
let message = await driver . findElement ( By . id ( 'message' ));
let value = await message . getText ();
assert . equal ( "Received!" , value );
});
after ( async () => await driver . quit ());
});
Show full example package dev.selenium.getting_started
import org.junit.jupiter.api.*
import org.junit.jupiter.api.Assertions.assertEquals
import org.openqa.selenium.By
import org.openqa.selenium.WebDriver
import org.openqa.selenium.chrome.ChromeDriver
import java.time.Duration
@TestInstance ( TestInstance . Lifecycle . PER_CLASS )
class FirstScriptTest {
private lateinit var driver : WebDriver
@Test
fun eightComponents () {
driver = ChromeDriver ()
driver . get ( "https://www.selenium.dev/selenium/web/web-form.html" )
val title = driver . title
assertEquals ( "Web form" , title )
driver . manage (). timeouts (). implicitlyWait ( Duration . ofMillis ( 500 ))
var textBox = driver . findElement ( By . name ( "my-text" ))
val submitButton = driver . findElement ( By . cssSelector ( "button" ))
textBox . sendKeys ( "Selenium" )
submitButton . click ()
val message = driver . findElement ( By . id ( "message" ))
val value = message . getText ()
assertEquals ( "Received!" , value )
driver . quit ()
}
}
Setting Up and Tearing Down
Java
Python
CSharp
Ruby
JavaScript
Kotlin Set Up <details class="mt-3">
<summary>Show full example</summary>
<div class="pt-2">
<div class="highlight"><pre tabindex="0" style="background-color:#f8f8f8;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-java" data-lang="java"><span style="display:flex;"><span><span style="color:#204a87;font-weight:bold">package</span><span style="color:#f8f8f8;text-decoration:underline"> </span><span style="color:#000">dev.selenium.getting_started</span><span style="color:#000;font-weight:bold">;</span><span style="color:#f8f8f8;text-decoration:underline">
import static org.junit.jupiter.api.Assertions.assertEquals ;
import java.time.Duration ;
import org.junit.jupiter.api.AfterEach ;
import org.junit.jupiter.api.BeforeEach ;
import org.junit.jupiter.api.Test ;
import org.openqa.selenium.By ;
import org.openqa.selenium.WebDriver ;
import org.openqa.selenium.WebElement ;
import org.openqa.selenium.chrome.ChromeDriver ;
public class UsingSeleniumTest {
WebDriver driver ;
@BeforeEach
public void setup () {
driver = new ChromeDriver ();
}
@Test
public void eightComponents () {
driver . manage (). timeouts (). implicitlyWait ( Duration . ofMillis ( 500 ));
driver . get ( "https://www.selenium.dev/selenium/web/web-form.html" );
String title = driver . getTitle ();
assertEquals ( "Web form" , title );
WebElement textBox = driver . findElement ( By . name ( "my-text" ));
WebElement submitButton = driver . findElement ( By . cssSelector ( "button" ));
textBox . sendKeys ( "Selenium" );
submitButton . click ();
WebElement message = driver . findElement ( By . id ( "message" ));
String value = message . getText ();
assertEquals ( "Received!" , value );
}
@AfterEach
public void teardown () {
driver . quit ();
}
}
<div class="text-end pb-2 mt-2">
<a href="https://github.com/SeleniumHQ/seleniumhq.github.io/blob/display_full/examples/java/src/test/java/dev/selenium/getting_started/UsingSeleniumTest.java#L19-L22" target="_blank">
<i class="fas fa-external-link-alt pl-2"></i>
<strong>View full example on GitHub</strong>
</a>
</div>
Tear Down <details class="mt-3">
<summary>Show full example</summary>
<div class="pt-2">
<div class="highlight"><pre tabindex="0" style="background-color:#f8f8f8;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-java" data-lang="java"><span style="display:flex;"><span><span style="color:#204a87;font-weight:bold">package</span><span style="color:#f8f8f8;text-decoration:underline"> </span><span style="color:#000">dev.selenium.getting_started</span><span style="color:#000;font-weight:bold">;</span><span style="color:#f8f8f8;text-decoration:underline">
import static org.junit.jupiter.api.Assertions.assertEquals ;
import java.time.Duration ;
import org.junit.jupiter.api.AfterEach ;
import org.junit.jupiter.api.BeforeEach ;
import org.junit.jupiter.api.Test ;
import org.openqa.selenium.By ;
import org.openqa.selenium.WebDriver ;
import org.openqa.selenium.WebElement ;
import org.openqa.selenium.chrome.ChromeDriver ;
public class UsingSeleniumTest {
WebDriver driver ;
@BeforeEach
public void setup () {
driver = new ChromeDriver ();
}
@Test
public void eightComponents () {
driver . manage (). timeouts (). implicitlyWait ( Duration . ofMillis ( 500 ));
driver . get ( "https://www.selenium.dev/selenium/web/web-form.html" );
String title = driver . getTitle ();
assertEquals ( "Web form" , title );
WebElement textBox = driver . findElement ( By . name ( "my-text" ));
WebElement submitButton = driver . findElement ( By . cssSelector ( "button" ));
textBox . sendKeys ( "Selenium" );
submitButton . click ();
WebElement message = driver . findElement ( By . id ( "message" ));
String value = message . getText ();
assertEquals ( "Received!" , value );
}
@AfterEach
public void teardown () {
driver . quit ();
}
}
<div class="text-end pb-2 mt-2">
<a href="https://github.com/SeleniumHQ/seleniumhq.github.io/blob/display_full/examples/java/src/test/java/dev/selenium/getting_started/UsingSeleniumTest.java#L45-L48" target="_blank">
<i class="fas fa-external-link-alt pl-2"></i>
<strong>View full example on GitHub</strong>
</a>
</div>
Set Up <details class="mt-3">
<summary>Show full example</summary>
<div class="pt-2">
<div class="highlight"><pre tabindex="0" style="background-color:#f8f8f8;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-py" data-lang="py"><span style="display:flex;"><span><span style="color:#204a87;font-weight:bold">from</span> <span style="color:#000">selenium</span> <span style="color:#204a87;font-weight:bold">import</span> <span style="color:#000">webdriver</span>
from selenium.webdriver.common.by import By
def test_eight_components ():
driver = setup ()
title = driver . title
assert title == "Web form"
driver . implicitly_wait ( 0.5 )
text_box = driver . find_element ( by = By . NAME , value = "my-text" )
submit_button = driver . find_element ( by = By . CSS_SELECTOR , value = "button" )
text_box . send_keys ( "Selenium" )
submit_button . click ()
message = driver . find_element ( by = By . ID , value = "message" )
value = message . text
assert value == "Received!"
teardown ( driver )
def setup ():
driver = webdriver . Chrome ()
driver . get ( "https://www.selenium.dev/selenium/web/web-form.html" )
return driver
def teardown ( driver ):
driver . quit ()
<div class="text-end pb-2 mt-2">
<a href="https://github.com/SeleniumHQ/seleniumhq.github.io/blob/display_full/examples/python/tests/getting_started/using_selenium_tests.py#L25-L28" target="_blank">
<i class="fas fa-external-link-alt pl-2"></i>
<strong>View full example on GitHub</strong>
</a>
</div>
Tear Down <details class="mt-3">
<summary>Show full example</summary>
<div class="pt-2">
<div class="highlight"><pre tabindex="0" style="background-color:#f8f8f8;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-py" data-lang="py"><span style="display:flex;"><span><span style="color:#204a87;font-weight:bold">from</span> <span style="color:#000">selenium</span> <span style="color:#204a87;font-weight:bold">import</span> <span style="color:#000">webdriver</span>
from selenium.webdriver.common.by import By
def test_eight_components ():
driver = setup ()
title = driver . title
assert title == "Web form"
driver . implicitly_wait ( 0.5 )
text_box = driver . find_element ( by = By . NAME , value = "my-text" )
submit_button = driver . find_element ( by = By . CSS_SELECTOR , value = "button" )
text_box . send_keys ( "Selenium" )
submit_button . click ()
message = driver . find_element ( by = By . ID , value = "message" )
value = message . text
assert value == "Received!"
teardown ( driver )
def setup ():
driver = webdriver . Chrome ()
driver . get ( "https://www.selenium.dev/selenium/web/web-form.html" )
return driver
def teardown ( driver ):
driver . quit ()
<div class="text-end pb-2 mt-2">
<a href="https://github.com/SeleniumHQ/seleniumhq.github.io/blob/display_full/examples/python/tests/getting_started/using_selenium_tests.py#L30-31" target="_blank">
<i class="fas fa-external-link-alt pl-2"></i>
<strong>View full example on GitHub</strong>
</a>
</div>
Set Up <details class="mt-3">
<summary>Show full example</summary>
<div class="pt-2">
<div class="highlight"><pre tabindex="0" style="background-color:#f8f8f8;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-rb" data-lang="rb"><span style="display:flex;"><span><span style="color:#8f5902;font-style:italic"># frozen_string_literal: true</span>
require 'selenium-webdriver'
RSpec . describe 'Using Selenium' do
it 'uses eight components' do
driver = Selenium :: WebDriver . for :chrome
driver . get ( 'https://www.selenium.dev/selenium/web/web-form.html' )
title = driver . title
expect ( title ) . to eq ( 'Web form' )
driver . manage . timeouts . implicit_wait = 500
text_box = driver . find_element ( name : 'my-text' )
submit_button = driver . find_element ( tag_name : 'button' )
text_box . send_keys ( 'Selenium' )
submit_button . click
message = driver . find_element ( id : 'message' )
value = message . text
expect ( value ) . to eq ( 'Received!' )
driver . quit
end
end
<div class="text-end pb-2 mt-2">
<a href="https://github.com/SeleniumHQ/seleniumhq.github.io/blob/display_full/examples/ruby/spec/getting_started/using_selenium_spec.rb#L7" target="_blank">
<i class="fas fa-external-link-alt pl-2"></i>
<strong>View full example on GitHub</strong>
</a>
</div>
Tear Down <details class="mt-3">
<summary>Show full example</summary>
<div class="pt-2">
<div class="highlight"><pre tabindex="0" style="background-color:#f8f8f8;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-rb" data-lang="rb"><span style="display:flex;"><span><span style="color:#8f5902;font-style:italic"># frozen_string_literal: true</span>
require 'selenium-webdriver'
RSpec . describe 'Using Selenium' do
it 'uses eight components' do
driver = Selenium :: WebDriver . for :chrome
driver . get ( 'https://www.selenium.dev/selenium/web/web-form.html' )
title = driver . title
expect ( title ) . to eq ( 'Web form' )
driver . manage . timeouts . implicit_wait = 500
text_box = driver . find_element ( name : 'my-text' )
submit_button = driver . find_element ( tag_name : 'button' )
text_box . send_keys ( 'Selenium' )
submit_button . click
message = driver . find_element ( id : 'message' )
value = message . text
expect ( value ) . to eq ( 'Received!' )
driver . quit
end
end
<div class="text-end pb-2 mt-2">
<a href="https://github.com/SeleniumHQ/seleniumhq.github.io/blob/display_full/examples/ruby/spec/getting_started/using_selenium_spec.rb#L26" target="_blank">
<i class="fas fa-external-link-alt pl-2"></i>
<strong>View full example on GitHub</strong>
</a>
</div>
### Set Up
Show full example const { By , Builder } = require ( 'selenium-webdriver' );
const assert = require ( "assert" );
describe ( 'First script' , function () {
let driver ;
before ( async function () {
driver = await new Builder (). forBrowser ( 'chrome' ). build ();
});
it ( 'First Selenium script with mocha' , async function () {
await driver . get ( 'https://www.selenium.dev/selenium/web/web-form.html' );
let title = await driver . getTitle ();
assert . equal ( "Web form" , title );
await driver . manage (). setTimeouts ({ implicit : 500 });
let textBox = await driver . findElement ( By . name ( 'my-text' ));
let submitButton = await driver . findElement ( By . css ( 'button' ));
await textBox . sendKeys ( 'Selenium' );
await submitButton . click ();
let message = await driver . findElement ( By . id ( 'message' ));
let value = await message . getText ();
assert . equal ( "Received!" , value );
});
after ( async () => await driver . quit ());
});
### Tear Down
Show full example const { By , Builder } = require ( 'selenium-webdriver' );
const assert = require ( "assert" );
describe ( 'First script' , function () {
let driver ;
before ( async function () {
driver = await new Builder (). forBrowser ( 'chrome' ). build ();
});
it ( 'First Selenium script with mocha' , async function () {
await driver . get ( 'https://www.selenium.dev/selenium/web/web-form.html' );
let title = await driver . getTitle ();
assert . equal ( "Web form" , title );
await driver . manage (). setTimeouts ({ implicit : 500 });
let textBox = await driver . findElement ( By . name ( 'my-text' ));
let submitButton = await driver . findElement ( By . css ( 'button' ));
await textBox . sendKeys ( 'Selenium' );
await submitButton . click ();
let message = await driver . findElement ( By . id ( 'message' ));
let value = await message . getText ();
assert . equal ( "Received!" , value );
});
after ( async () => await driver . quit ());
});
执行
Java
Python
CSharp
Ruby
JavaScript
Kotlin <details class="mt-3">
<summary>Show full example</summary>
<div class="pt-2">
<div class="highlight"><pre tabindex="0" style="background-color:#f8f8f8;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-md" data-lang="md"><span style="display:flex;"><span><span style="color:#000080;font-weight:bold"># Running all tests from Selenium python example
Follow these steps to run all test example from selenium python
1. Clone this repository
</span></span></span><span style="display:flex;"><span><span style="color:#4e9a06"></span>git clone https://github.com/SeleniumHQ/seleniumhq.github.io.git </span></span><span style="display:flex;"><span><span style="color:#4e9a06">
2. Navigate to python
directory
</span></span></span><span style="display:flex;"><span><span style="color:#4e9a06"></span>cd seleniumhq.github.io/examples/python </span></span><span style="display:flex;"><span><span style="color:#4e9a06">
3. Install dependencies using pip
</span></span></span><span style="display:flex;"><span><span style="color:#4e9a06"></span>pip install -r requirements.txt </span></span><span style="display:flex;"><span><span style="color:#4e9a06">
> if you are on a different python version, for example python3.x you may have to replace pip
with pip3
4. Run all tests
</span></span></span><span style="display:flex;"><span><span style="color:#4e9a06"></span>pytest </span></span><span style="display:flex;"><span><span style="color:#4e9a06">
> Please keep some patience - If you are doing it for the first time, it will take a little while to verify and download the browser drivers
## Execute a specific example
To run a specific Selenium Python example, use the following command:
bash </span></span></span><span style="display:flex;"><span><span style="color:#4e9a06"></span>pytest path/to/test_script.py </span></span><span style="display:flex;"><span><span style="color:#4e9a06">
Make sure to replace path/to/test_script.py
with the path and name of the example you want to run.
<div class="text-end pb-2 mt-2">
<a href="https://github.com/SeleniumHQ/seleniumhq.github.io/blob/display_full/examples/python/README.md#L35" target="_blank">
<i class="fas fa-external-link-alt pl-2"></i>
<strong>View full example on GitHub</strong>
</a>
</div>
<details class="mt-3">
<summary>Show full example</summary>
<div class="pt-2">
<div class="highlight"><pre tabindex="0" style="background-color:#f8f8f8;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-md" data-lang="md"><span style="display:flex;"><span><span style="color:#000080;font-weight:bold"># Running all tests from Selenium ruby example
Follow these steps to run all test example from selenium ruby
1. Clone this repository
</span></span></span><span style="display:flex;"><span><span style="color:#4e9a06"></span>git clone https://github.com/SeleniumHQ/seleniumhq.github.io.git </span></span><span style="display:flex;"><span><span style="color:#4e9a06">
2. Navigate to ruby
directory
</span></span></span><span style="display:flex;"><span><span style="color:#4e9a06"></span>cd seleniumhq.github.io/examples/ruby </span></span><span style="display:flex;"><span><span style="color:#4e9a06">
3. Install dependencies using bundler
</span></span></span><span style="display:flex;"><span><span style="color:#4e9a06"></span>bundler install </span></span><span style="display:flex;"><span><span style="color:#4e9a06">
4. Run all tests
</span></span></span><span style="display:flex;"><span><span style="color:#4e9a06"></span>bundle exec rspec </span></span><span style="display:flex;"><span><span style="color:#4e9a06">
> Please keep some patience - If you are doing it for the first time, it will take a little while to verify and download the browser drivers
# Execute a ruby script
Use this command to run a ruby script and follow the first script example
</span></span></span><span style="display:flex;"><span><span style="color:#4e9a06"></span>ruby example_script.rb </span></span><span style="display:flex;"><span><span style="color:#4e9a06">
<div class="text-end pb-2 mt-2">
<a href="https://github.com/SeleniumHQ/seleniumhq.github.io/blob/display_full/examples/ruby/README.md#L26" target="_blank">
<i class="fas fa-external-link-alt pl-2"></i>
<strong>View full example on GitHub</strong>
</a>
</div>
Mocha mocha runningTests.spec.js
npx npx mocha runningTests.spec.js
示例 在第一个脚本 一节中,我们了解了 Selenium 脚本的每一个组件。这里是使用 test runner 重新组织那个脚本的一个示例:
Java
Python
CSharp
Ruby
JavaScript
Kotlin package dev.selenium.getting_started ;
import static org.junit.jupiter.api.Assertions.assertEquals ;
import java.time.Duration ;
import org.junit.jupiter.api.AfterEach ;
import org.junit.jupiter.api.BeforeEach ;
import org.junit.jupiter.api.Test ;
import org.openqa.selenium.By ;
import org.openqa.selenium.WebDriver ;
import org.openqa.selenium.WebElement ;
import org.openqa.selenium.chrome.ChromeDriver ;
public class UsingSeleniumTest {
WebDriver driver ;
@BeforeEach
public void setup () {
driver = new ChromeDriver ();
}
@Test
public void eightComponents () {
driver . manage (). timeouts (). implicitlyWait ( Duration . ofMillis ( 500 ));
driver . get ( "https://www.selenium.dev/selenium/web/web-form.html" );
String title = driver . getTitle ();
assertEquals ( "Web form" , title );
WebElement textBox = driver . findElement ( By . name ( "my-text" ));
WebElement submitButton = driver . findElement ( By . cssSelector ( "button" ));
textBox . sendKeys ( "Selenium" );
submitButton . click ();
WebElement message = driver . findElement ( By . id ( "message" ));
String value = message . getText ();
assertEquals ( "Received!" , value );
}
@AfterEach
public void teardown () {
driver . quit ();
}
}
from selenium import webdriver
from selenium.webdriver.common.by import By
def test_eight_components ():
driver = setup ()
title = driver . title
assert title == "Web form"
driver . implicitly_wait ( 0.5 )
text_box = driver . find_element ( by = By . NAME , value = "my-text" )
submit_button = driver . find_element ( by = By . CSS_SELECTOR , value = "button" )
text_box . send_keys ( "Selenium" )
submit_button . click ()
message = driver . find_element ( by = By . ID , value = "message" )
value = message . text
assert value == "Received!"
teardown ( driver )
def setup ():
driver = webdriver . Chrome ()
driver . get ( "https://www.selenium.dev/selenium/web/web-form.html" )
return driver
def teardown ( driver ):
driver . quit ()
using System ;
using Microsoft.VisualStudio.TestTools.UnitTesting ;
using OpenQA.Selenium ;
using OpenQA.Selenium.Chrome ;
namespace SeleniumDocs.GettingStarted
{
[TestClass]
public class UsingSeleniumTest
{
[TestMethod]
public void EightComponents ()
{
IWebDriver driver = new ChromeDriver ();
driver . Navigate (). GoToUrl ( "https://www.selenium.dev/selenium/web/web-form.html" );
var title = driver . Title ;
Assert . AreEqual ( "Web form" , title );
driver . Manage (). Timeouts (). ImplicitWait = TimeSpan . FromMilliseconds ( 500 );
var textBox = driver . FindElement ( By . Name ( "my-text" ));
var submitButton = driver . FindElement ( By . TagName ( "button" ));
textBox . SendKeys ( "Selenium" );
submitButton . Click ();
var message = driver . FindElement ( By . Id ( "message" ));
var value = message . Text ;
Assert . AreEqual ( "Received!" , value );
driver . Quit ();
}
}
}
# frozen_string_literal: true
require 'selenium-webdriver'
RSpec . describe 'Using Selenium' do
it 'uses eight components' do
driver = Selenium :: WebDriver . for :chrome
driver . get ( 'https://www.selenium.dev/selenium/web/web-form.html' )
title = driver . title
expect ( title ) . to eq ( 'Web form' )
driver . manage . timeouts . implicit_wait = 500
text_box = driver . find_element ( name : 'my-text' )
submit_button = driver . find_element ( tag_name : 'button' )
text_box . send_keys ( 'Selenium' )
submit_button . click
message = driver . find_element ( id : 'message' )
value = message . text
expect ( value ) . to eq ( 'Received!' )
driver . quit
end
end
const { By , Builder } = require ( 'selenium-webdriver' );
const assert = require ( "assert" );
describe ( 'First script' , function () {
let driver ;
before ( async function () {
driver = await new Builder (). forBrowser ( 'chrome' ). build ();
});
it ( 'First Selenium script with mocha' , async function () {
await driver . get ( 'https://www.selenium.dev/selenium/web/web-form.html' );
let title = await driver . getTitle ();
assert . equal ( "Web form" , title );
await driver . manage (). setTimeouts ({ implicit : 500 });
let textBox = await driver . findElement ( By . name ( 'my-text' ));
let submitButton = await driver . findElement ( By . css ( 'button' ));
await textBox . sendKeys ( 'Selenium' );
await submitButton . click ();
let message = await driver . findElement ( By . id ( 'message' ));
let value = await message . getText ();
assert . equal ( "Received!" , value );
});
after ( async () => await driver . quit ());
});
下一步 使用你目前所学到的知识建立你自己的 Selenium 代码吧!
想要了解更多的功能特性,请继续阅读我们接下来的WebDriver 教程
Development Partners
Selenium Level Sponsors Support the Selenium Project Learn more or view the full list of sponsors.
© 2025 Software Freedom Conservancy 保留所有权利 关于这个文档