Skip to content

Instantly share code, notes, and snippets.

@vaidik
Last active December 19, 2015 05:39
Show Gist options
  • Save vaidik/5905762 to your computer and use it in GitHub Desktop.
Save vaidik/5905762 to your computer and use it in GitHub Desktop.
Get element's source only in Selenium or Marionette. Both Selenium and Marionette have APIs to get source of the entire page but not just the source of the `WebElement` or `HTMLElement`. This utility function fills that gap.
def element_html(driver, elements):
"""Return source of a particular HTML element on the page.
:param driver: webdriver or marionette object - the object you use
to drive your webdriver or marionette tests.
:param elements: Webdriver.remote.webelement.WebElement object or
marionette.marionette.HTMLElement object or
a list of WebElement or HTMLElement objects
:returns: string or list of strings of HTML element's source
"""
try:
from selenium.webdriver.remote.webelement import WebElement
except:
from marionette.marionette import HTMLElement
# just make this any type/class that is irrelevant
WebElement = str
finally:
if locals().get('HTMLElement', None) is None:
# just make this any type/class that is irrelevant
HTMLElement = str
def get_source(element):
return driver.execute_script("return arguments[0].innerHTML;", element)
ret_val = None
if isinstance(elements, list):
ret_val = []
for el in elements:
ret_val.append(get_source(el))
elif isinstance(elements, WebElement) or isinstance(elements, HTMLElement):
if HTMLElement != str:
elements = [elements]
ret_val = get_source(elements)
else:
raise Exception("Provide a webdriver's WebElement/marionette's "
"HTMLElement or a list of those objects.")
return ret_val
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment