selenium webdriver学习--通过id、name定位,输入内容,搜索,关闭操作;通过tagname查找元素
打开谷歌浏览器,输入不同的网站,搜索框的定位含有不同元素(有时为id,有时为name)
通过tagname查找元素
import java.util.List;import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver;import com.thoughtworks.selenium.Wait.WaitTimedOutException;@SuppressWarnings("deprecation") public class YsfTest_20180719{public static void main(String[] args) throws InterruptedException{//加载驱动器System.setProperty("webdriver.chrome.driver","C:/Program Files (x86)/Google/Chrome/Application/chromedriver.exe");//打开浏览器WebDriver driver = new ChromeDriver();//打开网站driver.get("https://www.baidu.com/");//通过id定位所搜框WebElement searchBox = driver.findElement(By.id("kw"));//输入内容searchBox.sendKeys("电影");//定位百度一下按钮WebElement searchButton = driver.findElement(By.id("su"));//点击百度一下 searchButton.submit();//等待5sThread.sleep(5000);//页面关闭 driver.close();//打开浏览器WebDriver driver2 = new ChromeDriver();//打开网站driver2.get("https://www.douban.com/");//通过name定位所搜框WebElement searchBox2 = driver2.findElement(By.name("q"));//输入内容searchBox2.sendKeys("电影");//点击百度一下 searchBox2.submit();//等待5sThread.sleep(5000);//页面关闭 driver2.close();//通过tagname查找元素//打开浏览器WebDriver driver3 = new ChromeDriver();//打开网站driver3.get("https://www.mi.com/");//通过tagname查找List<WebElement> scriptList = driver3.findElements(By.tagName("script")); //查找tagname为script的数量并输出System.out.println("there are "+scriptList.size()+" script");//等待5sThread.sleep(5000);//页面关闭 driver3.close();} }
本例主要用到//通过id定位所搜框
WebElement searchBox = driver.findElement(By.id("kw"));
//通过name定位所搜框
WebElement searchBox2 = driver2.findElement(By.name("q"));
//通过tagname查找
List<WebElement> scriptList = driver3.findElements(By.tagName("script"));