Selenium 入门

Selenium 简介

在这里插入图片描述

环境配置

  1. 安装JDK, 建议使用JDK1.8, 可以参照官网安装
  2. 安装eclipse
  3. 下载ChromeDriver:https://chromedriver.storage.googleapis.com/index.html, 根据自己的Chrome版本下载指定版本的driver
  4. 下载完成后将driver的路径放在path环境变量里
  5. 新建Maven项目,POM文件如下,注意Dependencies部分。
<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>com.stone.demos</groupId>
  <artifactId>SeleniumDemo</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <name>SeleniumDemo</name>
  <description>A demo project for Selenium</description>
  <dependencies>
  	<!-- https://mvnrepository.com/artifact/org.seleniumhq.selenium/selenium-java -->
	<dependency>
	    <groupId>org.seleniumhq.selenium</groupId>
	    <artifactId>selenium-java</artifactId>
	    <version>3.141.59</version>
	</dependency>
  	
  </dependencies>
</project>

代码展示

package com.stone.demos.seleniumdemo;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.ui.WebDriverWait;
import static org.openqa.selenium.support.ui.ExpectedConditions.*;

public class Demo {

	public static void main(String[] args) {
		WebDriver chrome = new ChromeDriver();
		WebDriverWait wait = new WebDriverWait(chrome, 30);
		
		try {
			//Visit www.sogou.com
			chrome.get("https://www.sogou.com");
			WebElement searchTextBox = wait.until(presenceOfElementLocated(By.cssSelector(".sec-input")));
			WebElement searchButton = wait.until(presenceOfElementLocated(By.cssSelector("#stb")));
			
			//input CSDN
			searchTextBox.clear();
			searchTextBox.sendKeys("CSDN");
			// click search button
			searchButton.click();
			
			// click the first link to CSDN home page
			WebElement theFirstLink = wait.until(presenceOfElementLocated(By.xpath("(//h3[@class='vrTitle'])[1]/a")));
			theFirstLink.click();
			
			assert chrome.getTitle().equalsIgnoreCase("CSDN-专业IT技术社区");
		}finally {
			chrome.quit();
		}
	}

}

代码讲解

  1. WebDriver chrome = new ChromeDriver(); 启动Chrome浏览器
  2. chrome.get(“https://www.sogou.com”); 访问搜狗网站
  3. 搜索“CSDN” searchTextBox.sendKeys(“CSDN”);
  4. 点击打开第一个搜索结果:theFirstLink.click();
  5. 验证站点的台头是“CSDN-专业IT技术社区”: assert chrome.getTitle().equalsIgnoreCase(“CSDN-专业IT技术社区”);
  6. 最后关闭浏览器
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值