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();
selenium+java实现简单前端自动化
最新推荐文章于 2024-05-20 20:58:48 发布