How to create a png w / selenium / phantomjs file from a string?

I am using selenium / phantomjs to create html png files in python. Is there a way to generate png from an html or filehandle string (instead of a website)? I searched for selenium documents and searched, but could not find an answer. I have:

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" 
+6
source share
4 answers

Phantomjs

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

Here is how to get a screenshot in phantomJS, I used phantomJS for some time.

You can find more information here.

Selenium

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

Hope this helps.

+11
source

Pure good old python - set content to any open page in target html - via JS. Example of your code:

 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" 
+4
source

Phantomjs

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

You set the content of the page using page.content then you execute it using page.render

Phantomjs node example

 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(); }); }); }); 
+2
source

It seems the lines

 f = open(myFile,'w') f.write(htmlString) 

They are problematic because the generated file is empty.

I fixed this issue with

 with open(myFile,'wt') as f: f.write(htmlString) 

or you may need to add

 f.close() to your code 
+1
source

Source: https://habr.com/ru/post/951062/


All Articles