Difference between text and innerHTML using Selenium

后端 未结 5 986
闹比i
闹比i 2020-11-22 15:40

Whats the difference between getting text and innerHTML when using selenium. Even though we have text under particular element, when we perform

5条回答
  •  孤街浪徒
    2020-11-22 16:02

    Chrome (i'm not sure about other browsers) ignores the extra spaces within the HTML code and displays as a single space.

    Example Text
    # notice the two spaces

    .get_attribute('innerHTML') will return the double-spaced text, which is what you would see when you inspect element), while .text will return the string with only 1 space.

    >>> print(element.get_attribute('innerHTML'))
    'Example  Text'
    >>> print(element.text)
    'Example Text'
    

    This difference is not trivial as the following will result in a NoSuchElementException.

    >>> arg = '//div[contains(text(),"Example Text")]'    
    >>> driver.find_element_by_xpath(arg)
    

    Similarly, .get_attribute('innerHTML') for the following returns Example Text, while .text returns Example Text.

    Example Text

提交回复
热议问题