本文介绍了在selenium webdriver(浏览器)中呈现HTTP响应(HTML内容)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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 ?

编辑
我可以想到的一种奇怪的方法是编写 response.text 添加到临时文件并在浏览器中打开该文件。请让我知道是否有更好的方法来做到这一点?

EDITA 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 ?

推荐答案

为了直接使用Selenium呈现一些HTML,可以使用get方法的数据方案:来自selenium的

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)

这篇关于在selenium webdriver(浏览器)中呈现HTTP响应(HTML内容)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-19 17:27