Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Selenium On Local HTML String

I am trying to run Selenium on a local HTML string but can't seem to find any documentation on how to do so. I retrieve HTML source from an e-mail API, so Selenium won't be able to parse it directly. Is there anyway to alter the following so that it would read the HTML string below:

Python Code for remote access:

from selenium import webdriver
from selenium.webdriver.common.keys import Keys

driver = webdriver.Firefox()
driver.get("http://www.python.org")
assert "Python" in driver.title
elem = driver.find_element_by_class_name("q")

Local HTML Code:

s = "<body>
        <p>This is a test</p>
        <p class="q">This is a second test</p>
     </body>"
like image 822
user2694306 Avatar asked Dec 29 '15 20:12

user2694306


Video Answer


1 Answers

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))
like image 57
jolancornevin Avatar answered Oct 12 '22 21:10

jolancornevin