Selenium2.0 Webdriver 隨筆
Webdriver can‘t action the element when the element is out of view
1. Scroll to the element
use JavaScript to scroll the element to view
[csharp] view plaincopy- ((IJavaScriptExecutor)driver).ExecuteScript("arguments[0].scrollIntoView(true);", element);
- ((IJavaScriptExecutor)driver).ExecuteScript("arguments[0].scrollIntoView(true);", element);
2. Use Location to view
Use LocationInView property need use RemoteWebdriver and RemoteWebElement
Code like:
[csharp] view plaincopy- RemoteWebdriver rw = new RemoteWebdriver();
- RemoteWebElement re = rw.FindelementOnPage(By.Id("id"));
- re.LocationInView;
- RemoteWebdriver rw = new RemoteWebdriver();
- RemoteWebElement re = rw.FindelementOnPage(By.Id("id"));
- re.LocationInView;
Keypress(string locator, string keySequence)
selenium.KeyPress("id=rd_A", "\\40")
display都有這些值,有none, inline,block...,我把none改成了block,也可以把visiblility:hidden改成visible
JavascriptExecutorj= (JavascriptExecutor)driver;
j.executeScript("document.findElementById(‘123‘).style.display=‘block‘;");
然後再WebElement.sendKeys ("c:\abc.txt");
xpath在定位更接近目標的節點時可用“//”和“/”分割路徑,“//”表示相對路徑,即可直接定位到元素,不管它的位置在哪;
“/”表示絕對路徑,即當前目錄下的直接子元素。
比如在 input 框中輸入某個字符也可以使用這個方法。
action.click(element).sendKeys(keysToSend)。
這個方法也可以合並成:
action.sendKeys(element,keysToSend);
在寫selenium自動化的過程中,經常會遇到這樣的問題:
1.在同一個頁面內做操作,比如點擊某個按鈕後,彈出一個框,再點擊另外一個按鈕,又彈出一個框
2.此時如果第一個click操作後,第二個click再點擊時,由於前一個彈出的框仍舊在前端顯示,就會出錯
3.在實際人工操作中,點擊出第一個框後,點擊一下空白區域,在點擊出現第二個框。因此,可以考慮一個點擊空白區域的方法
實現方法如下
/**
* 點擊空白區域:坐標(0,0)
*/
public static void clickBlankArea(WebDriver driver) {
Actions actions = new Actions(driver);
actions.moveByOffset(0, 0).click().build().perform();
}
讓driver先移動到一個空白位置(此處設為(0,0)坐標點),做一下點擊操作即可
Selenium2.0 Webdriver 隨筆