Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
455 views
in Technique[技术] by (71.8m points)

python - How do I generate a png file w/ selenium/phantomjs from a string?

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"
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

PhantomJS

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

This is how to get a screenshot in phantomJS, I've used phantomJS for some time now.

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...