2016-05-26 22 views
0

特定のdiv内のすべてのp要素のテキストを収集するためにSeleniumを使用します。 リストを使用中に気付きましたが、SeleniumはDOM全体をスキャンして空のテキストを保存しました。だから、私はDOMを反復し、空のテキストと等しくない値だけをjava.util.Iterator経由で格納したいと考えました。これは可能ですか? リストのアプローチ以外の方法が効率的ですか?Java Selenium WebDriverでのIteratorの使用

イテレータのアプローチ:

public static boolean FeatureFunctionsCheck(String Feature){ 
try 
{ 

    Iterator<WebElement> all = (Iterator<WebElement>) Driver.Instance.findElement(By.xpath("//a[contains(text()," + Feature + ")]/ancestor::h3/following-sibling::div/div[@class='navMenu']/p")); 

    boolean check = false; 
    while(all.hasNext() && check){ 

     WebElement temp = all.next(); 
     if(!temp.getText().equals("")) 
     { 

      Log.Info("Functions: " + temp.getText()); 
      all = (Iterator<WebElement>) Driver.Instance.findElement(By.xpath("//a[contains(text()," + Feature + ")]/ancestor::h3/following-sibling::div/div[@class='navMenu']/p")); 

     } 
     else 
      check = true; 
    } 

    return false; 
} 
catch(Exception e) 
{ 
    Log.Error("Failed()" + e); 
    return false; 
} 
} 

イテレータアプローチは、例外がスローされます...

java.lang.ClassCastException: org.openqa.selenium.remote.RemoteWebElement cannot be cast to java.util.Iterator 

リストのアプローチはこれが効率的なされている場合はわからないが、作品

public static boolean FeatureFunctionsCheck(String Feature){ 
try 
{ 
    List<WebElement> AllModelFunctions = new ArrayList<WebElement>(); 


    Log.Info("[Test-235]: Selecting Feature"); 
    for(WebElement element: AllModelFunctions){ 
     if(!element.getText().equals("")) 
     { 
      Log.Info("Functions: " + element.getText()); 
     } 
    } 
    return false; 
} 
catch(Exception e) 
{ 
    Log.Error("Failed()" + e); 
    return false; 
} 
} 

答えて

1

findElement戻り WebElement。あなたはおそらく行うことを意図してfindElementsを使用して、指定されたXPathとすべての要素を検索することです:

Driver.Instance.findElements(... 

はまた、構文はオーバー複雑になります。あなただけのリストを取得し、それを反復処理することができます

List<WebElement> elements = Driver.Instance.findElements(...); 
for(WebElement element : elements) { 
    if(!element.getText().equals("")) 
    { 
     Log.Info("Functions: " + element.getText()); 
    } 
} 

ところで、私は完全にDriver.Instanceは、ドライバのインスタンスであることを信頼する(通常はJavaで使用すると、クラスインスタンスのための首都を持っていないしているので、私は私がそれを正しく理解しているかどうかは分かりません)。より一般的な構文は次のようになります。

WebDriver driver = new FirefoxDriver(); // or another browser 
driver.findElements(...); 
// ... 
+0

リストは、すべての要素を格納してから、条件文に基づいてロギングします。しかし、空の文字列の格納を避けるために、リストに条件付きで要素を格納することができるかどうかを知りたい。 –

+0

実際の質問は、空でないテキストを選択するために '.../ancestor :: h3/following-sibling :: div/div [@ class = 'navMenu']/p'を変更する方法です。 –

+0

なぜなら、あなたが望むのが要素であれば、 '.../ancestor :: h3/following-sibling :: div/div [@ class = 'navMenu']/p [text()!= '']'空ではないテキストを使用していますか? –

関連する問題