2017-08-17 125 views
0

我是Selenium WebDriver的初學者,我在StackOverflow主頁上使用這個測試。這些將是我測試的步驟:如何在使用Java的Selenium WebDriver上將鼠標移動到元素上時關注元素?

  1. 首先,轉到StackOverflow的主頁。
  2. 然後,移動鼠標上用戶按鈕使得其將被聚焦。 (我們沒有去點擊它只是將鼠標懸停它。)
  3. 現在,發現屏幕上的有源元件(即這是 當前焦點的元素),然後點擊它。

我想要用戶按鈕被點擊,因爲它是目前的焦點,但沒有發生。而不是問題按鈕被點擊。 這是我爲同一測試編寫的代碼。

package insertCartridge; 

import java.util.concurrent.TimeUnit; 
import org.openqa.selenium.By; 
import org.openqa.selenium.Dimension; 
import org.openqa.selenium.WebDriver; 
import org.openqa.selenium.WebElement; 
import org.openqa.selenium.firefox.FirefoxDriver; 
import org.openqa.selenium.interactions.Actions; 

public class Practice { 
    public static void main(String[] args) throws InterruptedException { 
    // TODO Auto-generated method stub 
    System.setProperty("webdriver.gecko.driver", "D:\\SELENIUM\\geckodriver-v0.18.0-win64\\geckodriver.exe"); 
    WebDriver driver = new FirefoxDriver(); 
    driver.manage().timeouts().implicitlyWait(10,TimeUnit.SECONDS) ; 
    String baseUrl = "https://stackoverflow.com/"; 
    driver.get(baseUrl); 
    driver.manage().window().setSize(new Dimension(1920, 1080)); 
    WebElement Users = driver.findElement(By.xpath("/html/body/header/div/div[1]/nav/ol/li[5]")); 
    Thread.sleep(3000); 
    Actions builder = new Actions(driver); 
    builder.moveToElement(Users).perform(); 
    Thread.sleep(3000); 
    driver.switchTo().activeElement().click(); 
} 
} 

我不明白爲什麼我沒有得到預期的輸出。請幫忙。

+0

你不想點擊的用戶? –

+0

@PotnuruRavi,是的,我不想點擊USERS。只需將鼠標光標移動到它上面,然後找到活動元素(應該是USERS),然後單擊它。 – DG4

+0

找到元素(使用座標)並使用可以移動到「用戶」選項卡的操作。 Actions builder = new Actions(driver); builder.MoveToElement(WaitForElement(By.CssSelector(starElement)),location.X,location.Y); –

回答

1

我不知道爲什麼Actions類不聚焦的元素。它是一個問題或者是很多時候我在Firefox瀏覽器中遇到Actions類時遇到的問題。

你仍然有一個替代的方式來聚焦所需的元素,然後進行點擊的焦點元素上即JavascriptExecutor

在這裏,你是你的代碼:

JavascriptExecutor jse = (JavascriptExecutor) driver; 
jse.executeScript("document.getElementById('nav-users').focus();"); 

System.out.println(driver.switchTo().activeElement().getTagName());  
driver.switchTo().activeElement().click(); 
+0

有什麼方法可以通過Xpath獲取元素?因爲我在其中getElementById方法不起作用的Web應用程序中使用此方法。雖然您提出的方法在StackOverflow上運行良好。 – DG4

+0

@ DG4,是的,有一種方法可以使用xpath。你必須使用javascript的'evaluate()'。嘗試這和它'jse.executeScript(取代的xpath 「document.evaluate(\」 //一個[@ ID = 'NAV-用戶'] \」,文件,空,XPathResult.FIRST_ORDERED_NODE_TYPE,null)的.singleNodeValue.focus( );「);' – NarendraR

+0

我遵循了你的建議,但它在上面的代碼中使用xpath顯示錯誤。這是錯誤:無效的轉義序列(有效問卷是\ B \牛逼\ n \˚F\ r \」 \」 \\)很抱歉,如果這聽起來很愚蠢,我沒有使用JavaScript任何以往的經驗 – DG4

相關問題