python - 如何从字符串生成带有 selenium/phantomjs 的 png 文件?

标签 python selenium phantomjs

我正在使用 selenium/phantomjs 在 python 中创建 html 的 png 文件。有没有办法从 html 字符串或文件句柄(而不是网站)生成 png?我搜索了 selenium 文档并用谷歌搜索但找不到答案。我有:

htmlString = '<html><body><div style="background-color:red;height:500px;width:500px;">This is a png</div></body></html>'
myFile = 'tmp.html'
f = open(myFile,'w')
f.write(htmlString) 

from selenium import webdriver  

driver = webdriver.PhantomJS()
driver.set_window_size(1024, 768) 
#driver.get('https://google.com/') # this works fine
driver.get(myFile) # passing the file name or htmlString doesn't work...creates a blank png with nothing
driver.save_screenshot('screen.png') 
driver.quit()

print "png file created"

最佳答案

PhantomJS

var page = require('webpage').create();
page.open('http://github.com/', function () {
    page.render('github.png');
    phantom.exit();
});

这是在 phantomJS 中获取屏幕截图的方法,我已经使用 phantomJS 一段时间了。

您可以找到更多信息here.

Selenium

driver = webdriver.Chrome();
driver.get('http://www.google.com');
driver.save_screenshot('out.png');
driver.quit();

希望这对您有所帮助。

关于python - 如何从字符串生成带有 selenium/phantomjs 的 png 文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18067021/

相关文章:

python - 在 SQLite3 中添加列,然后填充它

python - 使用 for 循环和 if 语句的最长重复子串

python - 如何执行一个类(python)

java - 如何将实例值从一个类传递到包含测试注释方法的另一个类

Selenium 在 WebElement 中获取 WebElement

javascript - 如何调试 PhantomJS Javascript 测试?

python - Tensorflow:如何将 1 阶张量转换为 2 阶张量

java - 无法通过 Selenium 提交网站表单

javascript - 如何使用 PhantomJS 打开子框架中的链接?

selenium - headless 浏览器检测