Selenium selenium 学习二

wink_yang · 2019年05月08日 · 631 次阅读

一、自动化操作步骤

1.设置浏览器 driver
2.设置请求头 modify_headers,firebug 插件
3.初始化浏览器
4.删除 cookies
5.窗口最大化
6.设置窗口位置
7.打开链接
8.查找元素
9.处理业务逻辑
10.退出关闭窗口

二、选择器语法

1.根据 id 查找元素:By.id("username")
2.根据 class 查找元素:By.ClassName("username") class 存在空格的,必须写全
3.根据 name 查找元素:By.Name("username")
4.根据 css 样式查找元素:By.CssSelector("body a.jump") class 存在空格的,可以不用写全
5.根据 attr 属性查找元素:
By.xpath("//a[@target='_blank' and contains(text(),'regret')]")
By.xpath("//input[@class='button']")
By.xpath("//a[contains(text(),'Sign In')]")
6.按下回车键: enter.sendKeys(Keys.ENTER);
7.执行 js 操作

driver.executeScript("arguments[0].click()", elem); 
driver.executeScript("var ok=document.getElementById('ok');if(ok){ok.click();}");

8.多个窗口跳转(当前页面窗口点击跳转到新的标签页开启了一个新的窗口)

String currentHandle = driver.getWindowHandle();
Set<String> handles = driver.getWindowHandles();
for (String handle : handles)
{
    if (!handle.equals(currentHandle))
    {
        driver.switchTo().window(handle);
        //通过地址栏url切换窗口句柄
        if (type.equals(FindType.url))
        {
            if (driver.getCurrentUrl().contains(text))
            {
                break;
            }
        }

        //通过标题切换窗口句柄
        if (type.equals(FindType.title))
        {
            if (driver.getTitle().contains(text))
            {
                break;
            }
        }
    }
}

9.切换到 iframe 上去

driver.switchTo().frame("myIframe");
 WebElement div = driver.findElement(By.id("ihateyou"));
 this.click(div);
 wait.until(ExpectedConditions.alertIsPresent());
 // 点击确认alert框
 driver.switchTo().alert().accept();
 // 重新跳转到当前document上
 driver.switchTo().defaultContent();

以上总结了个人项目中 selenium 遇到的一些问题

暂无回复。
需要 登录 后方可回复, 如果你还没有账号请点击这里 注册