当前位置: 首页 > 科技观察

Java调用Selenium实现自动化测试

时间:2023-03-11 21:47:41 科技观察

Selenium简介Selenium是一款针对web应用的自动化测试工具。Selenium测试直接在浏览器中运行,就像真实用户一样。支持的浏览器包括IE(7、8、9、10、11)、MozillaFirefox、Safari、GoogleChrome、Opera等。Selenium特性开源,免费支持多浏览器:FireFox、Chrome、IE、Opera、Edge;多平台支持:Linux、Windows、MAC;多语言支持:Java、Python、Ruby、C#、JavaScript、C++;支持网页良好的支持;simple(简单的API),flexible(开发语言驱动);支持分布式测试用例执行。SeleniumAdvantage自动化测试:可以编写程序来自动化系统测试。爬虫:适用于爬取js混淆加密的网页。案例演示下载驱动包谷歌下载地址:http://chromedriver.storage.googleapis.com/index.html注意:尽量下载与自己的谷歌浏览器相似的版本,否则会出现不可描述的错误。引入依赖org.seleniumhq.seleniumselenium-java4.0.0com.google.guavaguavaRELEASEcode--"HelloWorld"privateWebDriverdriver;//浏览器驱动路径StringbrowserDriverPath="F:/IDEAWork/code-tools/webDriveSpider/chromedriver.exe";publicstaticvoidmain(String[]args)throwsException{Spiderapp=newSpider();app.setUp("https://news.baidu.com/");}publicvoidsetUp(Stringurl)throwsException{//开始chrome浏览System.setProperty("webdriver.chrome.driver",browserDriverPath);ChromeOptions选项=newChromeOptions();//无浏览器模式options.addArguments("--no-sandbox");driver=newChromeDriver(options);driver.manage().window().maximize();//最大化浏览器driver.manage().timeouts().implicitlyWait(30,TimeUnit.SECONDS);//设置操作超时时间,这个设置是全局的,即所有操作最多等待30sdriver.get(url);}看效果,很简单!爬虫方法代码ListwebElements=driver.findElements(By.className("a3"));for(WebElementwebElement:webElements){System.out.println(webElement.getText());}仅供教学参考,请勿违规使用规则的结果如下:text在框中输入内容并跳转到WebElementwebElement=driver.findElement(By.id("kw"));webElement.sendKeys("News");WebElementsearchBouuton=driver.findElement(By.id("su"));searchBouuton.click();每天一点知识,每天进步一点!