2013-02-20 47 views
17

如果文本存在,則點擊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]"} 
+0

請提供HTML代碼。 – 2016-11-28 12:46:00

回答

1

這裏我們可以使用嘗試,除了使用python網絡驅動程序的功能。看看下面的代碼

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() 
24

試試這個代碼:

用於檢查整個網頁文本存在下面的代碼。

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

else 
{ 
    //Click abc 
} 

如果您想檢查特定的網絡元素

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

else 
{ 
    //Click abc 
} 
+0

我經歷過,那些帶顯示的元素:沒有被返回爲空(沒有文本),即使它們包含文本(chrome開發工具顯示文本) – mojjj 2014-10-02 14:14:51

1

你需要用的「IsDisplayed」在嘗試捕捉上的文字。只有存在元素時才能調用「IsDisplayed」。

您可能還想重寫Implicit Time Out,否則try/catch將需要很長時間。

0

首先,這種類型的XPath和byLinkText是非常糟糕的定位器,並且會頻繁失敗。定位器應該是描述性的,獨特的,並且不太可能改變。重點是使用:

  1. ID
  2. CSSbetter performence than XPath
  3. 的XPath

然後你就可以在元件上使用getText()而日在整個頁面上(getPageSource())更具體。 try catch也是一個很好的做法isDisplayed()爲@Robbie陳述,或者更好的使用FluentWait找到元素:

// 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"); 
    }); 
0

試試這個下面的代碼: -

Assert.assertTrue(driver.getPageSource().contains(textOnThePage)); 
相關問題