如何从字符串生成png文件w/selenium/phantomjs?

2024-05-20 14:09:17 发布

您现在位置:Python中文网/ 问答频道 /正文

我使用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"

Tags: 文件字符串divgetpnghtmldriverselenium
3条回答

幻影

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

这是如何在phantomJS中获得屏幕截图的,我已经使用phantomJS一段时间了。

您可以找到更多信息here.

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

希望这有帮助。

幻影

var page = require('webpage').create();
page.content = '<html><body><p>Hello world</p></body></html>';
page.render('name.png');

使用page.content设置页面内容 然后使用page.render呈现它

Example using phantomjs-node

phantom.create(function (ph) {
  ph.createPage(function (page) {
      page.set('viewportSize', {width:1440,height:900})

      //like this
      page.set('content', html);

      page.render(path_to_pdf, function() { 
        //now pdf is written to disk.
        ph.exit();
      });
  });
});

纯好的旧python-通过JS将任何打开页面上的内容设置为目标html。以您的示例代码为例:

from selenium import webdriver

htmlString = '<html><body><div style="background-color:red;height:500px;width:500px;">This is a png</div></body></html>'

driver = webdriver.PhantomJS() # the normal SE phantomjs binding
driver.set_window_size(1024, 768)
driver.get('https://google.com/') # whatever reachable url
driver.execute_script("document.write('{}');".format(htmlString))  # changing the DOM

driver.save_screenshot('screen.png')   #screen.png is a big red rectangle :)
driver.quit()

print "png file created"

相关问题 更多 >