面試常見的selenium問題


1.如何切換iframe

  問題:如果你在一個default content中查找一個在iframe中的元素,那肯定是找不到的。反之你在一個iframe中查找另一個iframe元素或default content中的元素,那必然也定位不到

  基本步驟:先通過switch進入到iframe中,找到想找的元素,然后跳出來,進行其他的操作

  1).定位到iframe:WebElement IframeElement=driver.findElement(By.id(“frame”));

  2).切到這個iframe 里面:Driver.switch().frame(IframeElement);

  3).定位Iframe里面,你想要的元素:

  WebElement content=driver.findElement(By.className("CSS1Compat"));//在iframe中定位要找的元素

  content.sendKeys("cke_contents_content");//操作元素

  driver.switchTo().defaultContent();//跳出iframe,不跳出來是不能進行iframe外的操作的

2.如何處理彈窗

  1)處理彈窗就是一行代碼:driver.switchTo().alert().accept(),這個彈窗就關閉了;

  2)alert()方法知識:http://www.w3school.com.cn/jsref/met_win_alert.asp

3.如何處理上傳文件

  注:selenium不能處理windows窗口,它能提供的方法就是,把圖片或者文件的地址用sendkeys傳給【上傳文件/圖片】控件,對於含有input element的上傳, 我們可以直接通過sendkeys來傳入文件路徑

  1)找到上傳控件element,並輸入路徑:

  WebElement element = driver.findElement(By.id("cloudFax-attachment-form-upload-input"));

  element.sendKeys(getFilePath(text.txt));

  2)路徑的處理:

  private String getFilePath(String resource) {

  URL path = this.getClass().getResource(resource);

  return path.toString().replaceAll("file:/","");
  }

  附:看到另外一種簡單粗暴的處理方法,只需要3條代碼來處理此問題  

  WebElement uploadButton = driver.findElement(By.name("image"));

  String file="C:\\Users\\Public\\Pictures\\Sample Pictures\\flower.jpg";

  uploadButton.sendKeys(file);

相關鏈接:https://github.com/zhaohuif/-/wiki/Selenium-webdriver%E5%AD%A6%E4%B9%A0%E8%BF%87%E7%A8%8B%E4%B8%AD%E9%81%87%E5%88%B0%E7%9A%84%E9%97%AE%E9%A2%98

     http://www.51testing.com/html/55/n-860455.html

       http://ask.testfan.cn/article/26

4.如何切換瀏覽器窗口

  原理:webdriver是根據句柄來識別窗口的,因為句柄可以看做是窗口的唯一標識id。獲取新窗口的思路是:先獲取當前窗口句柄,然后獲取所有窗口的句柄,通過排除當前句柄,來確定新窗口的句柄。獲取到新窗口句柄后,通過switchto.window(newwindow_handle)方法,將新窗口的句柄當參數傳入就可以捕獲到新窗口了。

 //得到當前窗口的句柄 

  String currentWindow = dr.getWindowHandle();
  //得到所有窗口的句柄
  Set<String> handles = dr.getWindowHandles();
  //排除當前窗口的句柄,則剩下是新窗口(/*把Set集合轉換成Iterator*/)
  Iterator<String> it = handles.iterator();//迭代器
  while(it.hasNext()){
  String handle = it.next();
  if(currentWindow.equals(handle)) continue;
  driver.close();
  WebDriver window = dr.switchTo().window(handle);
  System.out.println("title,url = "+window.getTitle()+","+window.getCurrentUrl());

相關鏈接:http://jarvi.iteye.com/blog/1450626

     http://m.blog.csdn.net/article/details?id=8102135


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM