Selenium+Java(自动打开百度首页并执行搜索)

今日分享一个 使用selenium+java打开百度并进行搜索:直接贴代码 并附上注释

import java.util.concurrent.TimeUnit;

import org.openqa.selenium.By;

import org.openqa.selenium.WebDriver;

import org.openqa.selenium.chrome.ChromeDriver;

import org.openqa.selenium.firefox.FirefoxDriver;

import org.openqa.selenium.ie.InternetExplorerDriver;

public class baidutest {

public static void main(String[] args) throws InterruptedException {

      // 设置浏览器环境,要使用什么浏览器驱动

        System.setProperty("webdriver.chrome.driver","C:\\Program Files\\Chrome\\Application\\chromedriver.exe");   

      // 创建浏览器对象

        WebDriver driver = new ChromeDriver();

       driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);

       driver.get("https://www.baidu.com/");//要打开的网址

        Thread.sleep(1000);//睡眠1秒

        driver.findElement(By.id("kw")).clear();//模拟点击搜索文本框动作

        driver.findElement(By.id("kw")).sendKeys("selenium java");//模拟键盘输入要搜索的内容

        driver.findElement(By.id("su")).click();//模拟点击搜索按钮

        Thread.sleep(1000);

        System.out.println(driver.getTitle());//得到网页标题

        driver.quit();//退出

    }

}

到这里为止,模拟浏览器打开百度首页进行搜索并退出就完成了,是不是很简单。难点就在于定位元素哈。

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容