在selenium webdriver(浏览器)中呈现HTTP响应(HTML内容)

baw*_*nal 7 python selenium google-chrome google-chrome-devtools selenium-webdriver

我正在使用请求模块向网站发送GET和POST请求,然后处理他们的回复.如果Response.text符合某个标准,我希望它在浏览器中打开.目前我正在使用selenium包并通过selenium webdriver将请求重新发送到网页.但是,我觉得这个效率很低,因为我已经获得了一次响应,所以有没有办法将这个获得的Response对象直接渲染到通过selenium打开的浏览器中?

编辑 我能想到的一种hacky方式是将其写入response.text临时文件并在浏览器中打开.如果有比这更好的方法,请告诉我?

Flo*_* B. 8

要使用Selenium直接呈现某些HTML,您可以将数据方案与get方法一起使用:

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)
Run Code Online (Sandbox Code Playgroud)

或者您可以使用一段脚本编写页面:

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)
Run Code Online (Sandbox Code Playgroud)