Python Selenium On Local HTML String

Here was my solution for doing basic generated tests without having to make lots of temporary local files.

import json
from selenium import webdriver
driver = webdriver.PhantomJS()  # or your browser of choice

html = '''<div>Some HTML</div>'''
driver.execute_script("document.write('{}')".format(json.dumps(html)))
# your tests

If I understand the question correctly, I can imagine 2 ways to do this:

  1. Save HTML code as file, and load it as url file:///file/location. The problem with that is that location of file and how file is loaded by a browser may differ for various OSs / browsers. But implementation is very simple on the other hand.
  2. Another option is to inject your code onto some page, and then work with it as a regular dynamic HTML. I think this is more reliable, but also more work. This question has a good example.

If you don't want to create a file or load a URL before being able to replace the content of the page, you can always leverage the Data URLs feature, which supports HTML, CSS and JavaScript:

from selenium import webdriver

driver = webdriver.Chrome()
html_content = """
<html>
     <head></head>
     <body>
         <div>
             Hello World =)
         </div>
     </body>
</html>
"""

driver.get("data:text/html;charset=utf-8,{html_content}".format(html_content=html_content))