1

How can I find a text, or rather make sure it exists, on an html page regardless where it's located and what html tags it's surrounded by and its case? I just know a text and I want to make sure a page contains it and the text is visible.

Alan Coromano
  • 24,958
  • 53
  • 135
  • 205

1 Answers1

1

and the text is visible

This part is a crucial one - in order to determine element's visibility reliably, you would need the page rendered. Let's automate a real browser with selenium, get the element having the desired text and check if the element is displayed. Example in Python:

from selenium import webdriver 
from selenium.common.exceptions import NoSuchElementException


desired_text = "Desired text"

driver = webdriver.Chrome()
driver.get("url")

try:
    is_displayed = driver.find_element_by_xpath("//*[contains(., '%s')]" % desired_text).is_displayed()
    print("Element found")

    if is_displayed:
        print("Element is visible")
    else:
        print("Element is not visible")
except NoSuchElementException:
    print("Element not found")
alecxe
  • 462,703
  • 120
  • 1,088
  • 1,195
  • does `"//*[contains(., '%s')]` ignore the case of a text? it doesn't, right? – Alan Coromano Dec 16 '15 at 03:12
  • 1
    @AlanCoromano nope, but we can make it work too: http://stackoverflow.com/questions/8474031/case-insensitive-xpath-contains-possible. – alecxe Dec 16 '15 at 03:14
  • and if I wanted to check if multiple labels exist and visible, how would I do that? `"//*[contains(., 'label1')] and //*[contains(., 'label2')]"`? – Alan Coromano Dec 16 '15 at 03:21
  • @AlanCoromano just loop over them one by one and issue `find_element_by_xpath()` calls for every text you want to check on the page. – alecxe Dec 16 '15 at 03:25