selenium+java实现简单前端自动化

package test; 
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.*;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.interactions.Actions;
import java.util.concurrent.*;

public class baidu{
	public static void main(String[] args){
		//设定浏览器驱动
		System.setProperty("webdriver.chrome.driver","E://chromedriver.exe");
		webdriver driver = new ChromeDriver();
		
		//用驱动打开网页
		driver.get("https://www.xx.com/");
		
		//最大化网页窗口
		driver.manage().window().maximize();
		
		//通过id寻找元素并点击
		driver.findElement(By.id("xx")).click();
		//通过xpath寻找元素并点击(最常用)
		driver.findElement(By.xpath(".//*[@id='accountLogin']")).click();
		//通过页面的文本信息寻找并点击
		driver.findElement(By.linkText("领取")).click();
		
		//找到元素后将需要输入的东西进行发送
		driver.findElement(By.xpath(".//*[@id='username']")).sendKeys("123456");
		
		//当确认页面出现弹窗后,点击确定关闭弹窗
		driver.switchTo().alert().accept();

		//常见问题
		//1. 页面没有第一时间加载出来,导致定位不到元素。可以通过设置等待一段时间来让页面加载完成
        try {
        	Thread.sleep(3000);
        } catch(InterruptedException e) {
        	e.printStackTrace();
        } 
		//2. 需要定位的元素不在当前所在的frame里,需要切换到正确的frame
		WebElement element =driver.switchTo().frame("pagebody_iframe").findElement(By.xpath("//*[@id='applyId']"));
		//3. 当通过页面的文本信息定位元素的时候,有时需要定位的元素没有在当前能看到的页面中,可以通过操作键盘让滚动条滚动来让元素展示出来(未完待续)
        Actions actions = new Actions(driver);
        actions.sendKeys(Keys.DOWN).perform();
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值