2

I got something like this:

<div id=soandso>
  Having a 
  <img src="cat.gif" alt="Meow">
  always helps
</div>

I have no problems finding the div element, when I invoke getText() I would wish to receive "Having a Meow always helps", but instead I get the text without the alt (Meow) description.

I agree this is the expected behaviour, but this is not what I need.

How can I preferably inline the alt text or at least get the text chunks in sequence with the inline image to verify the proper placement of the image inside the text?

Stefan
  • 990
  • 1
  • 6
  • 10
  • I found a solution here: http://stackoverflow.com/questions/12325454/how-to-get-text-of-an-element-in-selenium-webdriver-via-the-python-api-without - basically suggests that you use jQuery to get the text within the div. – Richard Jan 12 '14 at 16:51
  • 1
    Boy this is ugly, but should make it work. If you add your comment as answer, I will mark it sucesfull.Thanks! – Stefan Jan 13 '14 at 09:14

2 Answers2

4

selenium-webdriver works that way in both scenarios,

  1. considers "alt" as attribute of image tag and not as element text for Div.
  2. Considers "Having a always helps" as innerText of Div element.

i would suggest....to extract the Div text and img (alt) text separately. if text follows a pattern, try to identify sequence after or before which image attribute will be displayed.

WebElement Div_elem=Driver.findElement(By.id("soandso"));
String Div_text = Div_elem.getText();
String img_text=Div_elem.findElement(By.tagName("img")).getAttribute("alt");

would be glad if it helps

Anuragh27crony
  • 2,957
  • 1
  • 19
  • 29
2

I found a solution here: How to get text of an element in Selenium WebDriver (via the Python api) without including child element text?

His suggested solution:

def get_text_excluding_children(driver, element):
    return driver.execute_script("""
    return jQuery(arguments[0]).contents().filter(function() {
        return this.nodeType == Node.TEXT_NODE;
    }).text();
    """, element)

The element passed to the function can be something obtained from the find_element...() methods (i.e. it can be a WebElement object).

  • basically suggests that you use jQuery to get the text within the div.
Community
  • 1
  • 1
Richard
  • 8,961
  • 3
  • 38
  • 47