selenium for java 基本使用

selenium 使用

maven

  <!-- seleium -->
	 <properties>
        <selenium.version>4.18.1</selenium.version>
    </properties>

    <dependency>
        <groupId>org.seleniumhq.selenium</groupId>
        <artifactId>selenium-java</artifactId>
        <version>${
   selenium.version}</version>
    </dependency>

demo Code

package com.dsp.business.service;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.dsp.common.base.BaseConstant;
import org.apache.commons.lang3.time.DateUtils;
import org.openqa.selenium.Cookie;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.devtools.DevTools;
### 如何使用 SeleniumJava 进行 Web 自动化测试 #### 准备工作环境 为了能够顺利运行基于 Selenium 的自动化测试脚本,需要配置好开发环境。这通常意味着安装 JDK (Java Development Kit),设置 Maven 构建工具,并通过修改 `pom.xml` 文件来引入必要的依赖项。 对于 Selenium WebDriver,在项目的 `pom.xml` 中应加入如下所示的依赖声明[^2]: ```xml <dependencies> <dependency> <groupId>org.seleniumhq.selenium</groupId> <artifactId>selenium-java</artifactId> <version>3.5.3</version> </dependency> </dependencies> ``` #### 编写简单的自动化测试案例 一旦项目结构搭建完毕并导入了所需的库之后,就可以编写第一个自动化测试类了。下面是一个基本的例子,展示了如何启动浏览器实例、访问网页以及执行简单交互: ```java import org.junit.After; import org.junit.Before; import org.junit.Test; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; public class SimpleWebTest { private WebDriver driver; @Before public void setUp() { System.setProperty("webdriver.chrome.driver", "path/to/chromedriver"); driver = new ChromeDriver(); } @After public void tearDown() { if(driver != null){ driver.quit(); } } @Test public void testSimpleSearchFunctionality(){ String baseUrl = "http://www.example.com"; driver.get(baseUrl); WebElement searchBox = driver.findElement(By.name("q")); searchBox.sendKeys("Selenium with JUnit"); WebElement submitButton = driver.findElement(By.xpath("//input[@type='submit']")); submitButton.click(); try{ Thread.sleep(3000); // Wait for page load or results to appear. }catch(Exception e){ e.printStackTrace(); } boolean isResultFound = !driver.findElements(By.partialLinkText("Selenium")).isEmpty(); assert(isResultFound); } } ``` 这段代码定义了一个名为 `SimpleWebTest` 的JUnit 测试类,其中包含了三个主要的方法:初始化 (`setUp`) 方法用来创建一个新的 Chrome 浏览器会话;清理 (`tearDown`) 方法负责关闭浏览器窗口;而实际的测试逻辑则放在标注有 `@Test` 注解的方法里实现。此方法模拟了一次搜索引擎查询的过程,并验证返回页面上是否存在预期的内容[^1]。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

sparrow6902

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值