Selenium Webdriver——去哪儿网输入实例
1.对出发地方和到达地方进行Xpath定位,这里采用了Xpath的text() 函数进行定位
用following::sibling选择当前元素后的兄弟元素,比如出发框的Xpath表达式如下:
.//*[text()= '出发']/following-sibling::input"
也可以用下面Xpath
//div[@id='js_flighttype_tab_domestic']//input[@name='fromCity']
1 /** 2 * @author Hjianhui 3 * 12306 2016-08-05 4 * 5 */ 6 public class test{ 7 8 public static void main(String[] args) { 9 10 WebDriver driver = new FirefoxDriver(); 11 12 try{ 13 driver.get("http://www.qunar.com/"); 14 driver.manage().window().maximize(); 15 //输入出发地方 16 driver.findElement(By.xpath(".//*[text()= '出发']/following-sibling::input")).clear(); 17 driver.findElement(By.xpath(".//*[text()= '出发']/following-sibling::input")).sendKeys("北京"); 18 19 ////输入到达地方 20 driver.findElement(By.xpath(".//*[text()= '到达']/following-sibling::input")).clear(); 21 driver.findElement(By.xpath(".//*[text()= '到达']/following-sibling::input")).sendKeys("广州"); 22 23 if(isElementPresent(driver, By.xpath(".//*[@id='closeXI20']"))) 24 driver.findElement(By.xpath(".//*[@id='closeXI20']")).click(); 25 26 driver.findElement(By.id("js_domestic_fromdate")).clear(); 27 driver.findElement(By.id("js_domestic_fromdate")).sendKeys("2016-08-20"); 28 29 //点击立即搜索 30 driver.findElement(By.xpath(".//span[@class = 'p_btn']/button")).click(); 31 32 }catch (Exception e){ 33 e.printStackTrace(); 34 } 35 driver.quit(); 36 } 37 38 public static boolean isElementPresent(WebDriver driver, By by) { 39 try { 40 driver.manage().timeouts().implicitlyWait(1, TimeUnit.SECONDS); 41 driver.findElement(by); 42 return true; 43 } catch (NoSuchElementException e) { 44 return false; 45 } 46 } 47 }
由于在输入到达地方的时候,可能会有下图挡住了立即搜索,导致立即搜索不可见,因此用isElementPresent()函数判断该图下的右上角图标是否出现,如果出现,点击取消他,然后再点击立即搜索