selenium自动化

selenium自动化

1、废话不多说,上代码(有注释)

public static void main(String args[]) {
        //加载谷歌的驱动  其他驱动同样道理  先引入驱动,再构建环境
        File file = new File("C:\\Users\\acer\\Desktop\\chromedriver_win32\\chromedriver.exe");
        System.setProperty("webdriver.chrome.driver", file.getAbsolutePath());
        webDriver = new ChromeDriver();

        try {
            //打开指定页面        使用谷歌打开一个新的页面
            webDriver.get("https://www.baidu.com/");
            //睡眠3秒 防止加载失败
            Thread.sleep(3000);
//            String windowHandle = webDriver.getWindowHandle();//获取当前句柄
            //为搜索框赋值
            webDriver.findElement(By.id("kw")).sendKeys("远方的姑娘你可知道");
            //点击搜索
            webDriver.findElement(By.id("su")).click();
            //睡眠1秒
            Thread.sleep(1000);
            //使用xpath选择器 选取所包含的所有标签内容
            List<WebElement> a = webDriver.findElements(By.xpath("/html/body/div[1]/div[5]/div[1]/div[3]/div"));
            int size = a.size();
            //循环所获取的内容
            for (int i=0;i<size;i++){
                WebElement webElement = a.get(i);
                //根据className()定位,获取内容
                String a1 = webElement.findElement(By.className("t")).getText();
                System.out.println(a1);
                //睡眠1秒
                Thread.sleep(1000);
                //使用linkText()定位,然后点击打开链接
                webElement.findElement(By.linkText(a1)).click();
            }
        } catch (Exception e) {
//            webDriver.quit();//退出  既关闭所打开的浏览器
            System.out.println(e.getMessage());
        }
    }

2、效果图

所打开的页面:
打开的页面
控制台输出:
控制台输出的标题内容

3、其他常用的方法与选择器

                webElement.click();//点击
                webElement.getAttribute("");//获取属性值
                webElement.getText();//获取所在标签中的所有内容
                webElement.getTagName();//获取标签名字
                webElement.findElement(By.xpath(""));//xpath选择器
                webElement.findElement(By.id(""));//id选择器
                webElement.findElement(By.name(""));//name选择器
                webElement.findElement(By.tagName(""));//标签选择器
                webElement.findElement(By.cssSelector(""));//css选择器
                webElement.findElement(By.className(""));//class选择器
                webElement.findElement(By.linkText(""));//内容选择器
                webElement.findElement(By.partialLinkText(""));//也是内容选择器
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值