bawejakunal
bawejakunal

Reputation: 1708

Render HTTP Response(HTML content) in selenium webdriver(browser)

I am using Requests module to send GET and POST requests to websites and then processing their responses. If the Response.text meets a certain criteria, I want it to be opened up in a browser. To do so currently I am using selenium package and resending the request to the webpage via the selenium webdriver. However, I feel it's inefficient as I have already obtained the response once, so is there a way to render this obtained Response object directly into the browser opened via selenium ?

EDIT A hacky way that I could think of is to write the response.text to a temporary file and open that in the browser. Please let me know if there is a better way to do it than this ?

Upvotes: 10

Views: 6921

Answers (1)

Florent B.
Florent B.

Reputation: 42528

To directly render some HTML with Selenium, you can use the data scheme with the get method:

from selenium import webdriver
import requests

content = requests.get("http://stackoverflow.com/").content

driver = webdriver.Chrome()
driver.get("data:text/html;charset=utf-8," + content)

Or you could write the page with a piece of script:

from selenium import webdriver
import requests

content = requests.get("http://stackoverflow.com/").content

driver = webdriver.Chrome()
driver.execute_script("""
  document.location = 'about:blank';
  document.open();
  document.write(arguments[0]);
  document.close();
  """, content)

Upvotes: 14

Related Questions