I am using selenium/phantomjs to create png files of html in python. Is there a way to generate the png from an html string or filehandle (instead of a website)? I've searched through the selenium docs and googled but couldn't 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"
PhantomJS
You set the content of the page using
page.content
Then you render it usingpage.render
Example using phantomjs-node
It seems the lines
Are problematic, as the generated file is empty.
I fixed this issue with
or you might have to add a
PhantomJS
This is how to get a screenshot in phantomJS, I've used phantomJS for some time now.
You can find more information here.
Selenium
Hope this helps.
Pure good old python - set the content on any opened page to your target html - through JS. Taking your example code: