2016-12-16 60 views
1

我正在開發一個程序來自動化一些表單填充,我使用Selenium。自開始以來一直困擾我的問題是,如果這項工作是,應該點擊按鈕的指令不起作用並且不返回任何錯誤。這是隨機發生的,但是在我第一次運行該程序時,它會更頻繁地發生。Selenium發現元素,但隨機不點擊一個元素,雖然它在Firefox上這麼說

基本上驅動程序必須進入一個站點,用登錄名填寫一個彈出窗口,然後當第一頁加載時,必須單擊一個按鈕,這將打開第二頁。會發生什麼情況是,如果不打開第二頁,驅動程序已經在尋找屬於它的元素。

起初,我認爲瀏覽器和驅動程序可能會與驅動程序比瀏覽器更快並且不知何故搞亂整個過程而不同步。我試圖用半秒鐘的時間來糾正這個問題。還實施了15秒的隱含等待。

沒有任何改進,我決定檢查是否找到第一個元素。我插入了一行來將按鈕上的文本打印到控制檯,並且它被正確打印。下一行是單擊該按鈕,雖然驅動程序不檢索錯誤,但在瀏覽器上只加載第一頁。

最後但並不是最少嘗試找到所有具有該xpath的元素,但該列表只有一個元素。

因此,總而言之,找到第一個元素,點擊指令不會返回錯誤,但仍不點擊該按鈕。這是隨機發生的。

下面是我使用的代碼的相關部分:

tester.manage().timeouts().implicitlyWait(15, TimeUnit.SECONDS); 
    tester.get(website); 
     Thread.sleep(1000); 

     //Bypasses login pop-up window 
     try 
     { 
      bypassLogin(username, password); 
     } 
     catch(Exception e) 
     { 
      handler(e.getMessage(), null); 
      finisher(tester, br, br2, pathGecko, pathTemplate); 
     } 

     //Sleep in order to synchronize driver and browser 
     Thread.sleep(1000); 

     while((reader = br2.readLine()) != null) 
     { 
      tempOrig = new StringBuilder() 
          .append(tempOrig) 
          .append(reader) 
          .toString(); 
     } 

     //Enters the body frame, with the elements to work with 
     try 
     { 
      tester.switchTo().frame("portal_header"); 
      List <WebElement> LClick = tester.findElements(By.xpath(".//*[@id='2']/a")); 
      System.out.println(LClick.size()); //Returns 1 
      tester.findElement(By.xpath(".//*[@id='2']/a")).getText(); //Returns the correct value 
      tester.findElement(By.xpath(".//*[@id='2']/a")).click(); 
      tester.switchTo().defaultContent(); 
      tester.switchTo().frame("portal_body"); 
     } 
     catch(Exception e) 
     { 
      handler(e.getMessage(), null); 
      finisher(tester, br, br2, pathGecko, pathTemplate); 
     } 
+0

嘗試使用JavaScript的點擊。 'IWebElement element = tester.FindElement(By.xpath(「.//*[@ id ='2']/a」)); IJavaScriptExecutor js =(IJavaScriptExecutor)測試程序; js.ExecuteScript(「arguments [0] .click();」,element);'使用新版本的Firefox和Gecko驅動程序時,我遇到了點擊按鈕的問題。這解決了我的問題。請試一試。代碼是用C#編寫的。 – Sudeepthi

回答

0

試試這個,檢查

WebDriverWait wait = new WebDriverWait(tester, 15); 
boolean bool = tester.findElement(By.xpath(".//*[@id='2']/a")).isDisplayed(); 
System.out.print(bool); 
wait.until(ExpectedConditions.elementToBeClickable(By.xpath(".//*[@id='2']/a"))); 
tester.findElement(By.xpath(".//*[@id='2']/a")).click(); 

還要檢查瀏覽器版本和硒版本