25

テキストが存在する場合は をクリックし、xyzそうでない場合は をクリックしますabc

私は以下のifステートメントを使用しています:

if(driver.findElement(By.xpath("/html/body/div[2]/div/div/div/div/div/div/table/tbody/tr[6]/td[2]")).isDisplayed())
{    
    driver.findElement(By.linkText("logout")).getAttribute("href");          
} else {          
    driver.findElement(By.xpath("/html/body/div/div/div/a[2]")).click();
}

スクリプトは次のエラー メッセージで失敗します。

Unable to locate element: {"method":"xpath","selector":"/html/body/div[2]/div/div/div/div/div/div/table/tbody/tr[6]/td[2]"}
4

5 に答える 5

33

このコードを試してください:

以下のコードは、Web ページ全体でテキストの存在を確認するために使用されます。

if(driver.getPageSource().contains("your Text"))
{
    //Click xyz
}

else
{
    //Click abc
}

特定の Web 要素のテキストを確認したい場合

if(driver.findElement(By.id("Locator ID")).getText().equalsIgnoreCase("Yor Text"))
{
    //Click xyz
}

else
{
    //Click abc
}
于 2013-02-20T08:53:18.060 に答える
1

まず第一に、このタイプの XPath は非常に不適切byLinkTextなロケーターであり、頻繁に失敗します。ロケーターは、説明的で、一意で、変更される可能性が低い必要があります。優先して使用すること:

  1. ID
  2. クラス
  3. CSS ( XPath よりも優れたパフォーマンス)
  4. XPath

次に、より具体的なgetText()ページ全体 ( ) ではなく、要素に対して使用できます。@Robbieが述べたように、またはFluentWaitを使用して要素を見つけることもお勧めします。getPageSource()try catchisDisplayed()

// Waiting 10 seconds for an element to be present on the page, checking
// for its presence once every 1 second.
Wait<WebDriver> wait = new FluentWait<WebDriver>(driver)
    .withTimeout(10, SECONDS)
    .pollingEvery(1, SECONDS)
    .ignoring(StaleElementReferenceException.class)
    .ignoring(NoSuchElementException.class)
    .ignoring(ElementNotVisibleException.class)

次に、次のように使用します。

wait.until(x -> {
     WebElement webElement = driverServices.getDriver().findElement(By.id("someId"));
     return webElement.getText();
  });

wait.until(x -> {
     WebElement webElement = driverServices.getDriver().findElement(By.id("someOtherId"));
     return webElement.getAttribute("href");
  });
于 2016-11-15T10:31:39.517 に答える
1

"IsDisplayed" を try キャッチでラップする必要があります。「IsDisplayed」は、要素が存在する場合にのみ呼び出すことができます。

Implicit Time Out もオーバーライドしたい場合があります。オーバーライドしないと、try/catch に時間がかかります。

于 2013-02-20T13:38:29.357 に答える
1

ここでは、Python Web ドライバーを使用して関数を除いて、try を使用できます。コードの下を参照してください

webtable=driver.find_element_by_xpath("xpath value")
print webtable.text
try:
   xyz=driver.find_element_by_xpath(("xpath value")
   xyz.click()

except:
   abc=driver.find_element_by_xpath(("xpath value")
   abc.click()
于 2013-02-20T08:33:54.723 に答える
0

以下のコードを試してください:-

Assert.assertTrue(driver.getPageSource().contains(textOnThePage));
于 2016-12-21T18:25:49.987 に答える