2015-11-26 85 views
2

我想檢查使用Selenium(Python如果有問題)在HTML頁面上的某些文本(如「獨角獸」)是否可見。檢查文本是否在HTML元素的頁面上可見

然而,對於不相關的原因的頁面具有以下結構(簡化):

<div> 
    <span style="display: none">A</span> <span style="display: none">unicorn</span> 
</div> 

Lettuce WebdriverAloe Webdriver使用的檢查是:

driver.find_elements_by_xpath(
    '//*[contains(normalize-space(.),"{content}")'.format(text)) 

,然後檢查is_displayed返回的元件。但是,這將找到外部div元素,並且其文本將包含搜索的字符串,即使該字符串實際上對用戶不可見。

如何檢查頁面上的某些文字是可見即使它跨越多個元素?

各自的錯誤:Aloe Webdriver bugLettuce Webdriver bug

+0

你可以使用美麗的可能...看到這個答案:http://stackoverflow.com/a/27115266/499581 –

+0

這需要我重新實現一個CSS分析器,因爲實際的網頁可能會使用類而不是簡單的'顯示:無'。 – Koterpillar

回答

0

這是一個困難的情況。對於你給出的具體例子,下面的代碼應該可以工作。代碼基本上將「獨角獸」分成兩個單詞並找出各個元素。找到各個跨度標籤後,找到每個元素的父項並進行比較以獲得相等性。如果父母相等,則每個單獨的元素用於顯示屬性。

public class ComplicatedSearch { 

    public static void main(String[] args) { 
     WebDriver driver = new FirefoxDriver(); 
     driver.get("url"); 

     // Look if "A unicorn" occurs within a single element 
     WebElement element = getElement(driver, "A unicorn"); 
     if (element != null) { 
      if (element.isDisplayed()) { 
       System.out.println("Text is displayed"); 
      } 
     } 

     // Split "A unicorn" into 2 String and find the individual elements 
     WebElement part1 = getElement(driver, "A"); 
     WebElement part2 = getElement(driver, "unicorn"); 

     if (part1 != null && part2 != null) { 
      // find the parents of part1 and part2 and compare whether they are 
      // equal 
      if (findParent(driver, "A").equals(findParent(driver, "unicorn"))) { 
       // if parents are equal, check if both elements are displayed 
       if (part1.isDisplayed() && part2.isDisplayed()) { 
        System.out.println("Text is displayed"); 
       } else { 
        System.out.println("Text is not displyed"); 
       } 
      } 
     } 
    } 

    private static WebElement getElement(WebDriver driver, String keyword) { 
     try { 
      return driver.findElement(By.xpath("//*[.='" + keyword + "']")); 
     } catch (NoSuchElementException e) { 
      return null; 
     } 
    } 

    private static WebElement findParent(WebDriver driver, String keyword) { 
     try { 
      return driver.findElement(By.xpath("//*[.='" + keyword + "']/..")); 
     } catch (NoSuchElementException e) { 
      return null; 
     } 
    } 
} 

爲了使這種情況通用很多努力和許多條件將不得不合並。快樂編碼!

+0

謝謝你的回答。類似這樣的事情是我爲解決我眼前的問題而做的,但我認爲它不適用於一般情況。 – Koterpillar

相關問題