3

I need to write a python script which opens a website and when the website is completly opened it takes a screenshot of the opened website.

I wrote sth like this:

import webbrowser
import wx

wx.App()
link = "http://stackoverflow.com/questions"
webbrowser.get('firefox %s').open_new_tab(link)
screen = wx.ScreenDC()
size = screen.GetSize()
bmp = wx.EmptyBitmap(size[0], size[1])
mem = wx.MemoryDC(bmp)
mem.Blit(0, 0, size[0], size[1], screen, 0, 0)
del mem
bmp.SaveFile('screenshot.png', wx.BITMAP_TYPE_PNG)

It only opens a new tab in firefox but it doesnt take a screenshot of it :(

I want the solution to be cross-platform. Thanks for any help:)

EDIT:

The main problem here is that the script musnt take a picture BEFORE my webpage is completly opened. How to solve that issue?

Katie
  • 3,517
  • 11
  • 36
  • 49
  • 1
    I don't know what your `webbrowser` module is capable of. If there isn't any kind of callback from the browser to the controlling Python script indicating the page load has finished, then you have only one option left: wait a constant time and make it long enough: e.g. `time.sleep(5)`. – Dr. Jan-Philip Gehrcke Sep 24 '12 at 12:35

3 Answers3

2

I believe that you need different solutions for different operating systems. Use sys.platform to find out on which platform you are on. The rest you have to figure out yourself, but a quick internet search revealed:

  • On Linux systems, you can then take a screenshot as described here:

Take a screenshot via a python script. [Linux]

  • On Windows systems, you can base your solution on this answer:

Fastest way to take a screenshot with python on windows

  • On Mac systems, this will help:

Take screenshot in Python on Mac OS X

Community
  • 1
  • 1
Dr. Jan-Philip Gehrcke
  • 33,287
  • 14
  • 85
  • 130
1

According to this question, you should be able to use ImageGrab to take a screenshot. Since ImageGrab uses PIL, this should be cross-platform. Here is some sample code to get you on your way

Hope this helps

Community
  • 1
  • 1
inspectorG4dget
  • 110,290
  • 27
  • 149
  • 241
  • ok I will try it but still exists the problem that my script takes a screenshot BEFORE my webpage is completly opened :( – Katie Sep 24 '12 at 10:55
  • 1
    Look at [this question])http://stackoverflow.com/questions/3636008/wait-for-web-page-to-load-completely-using-python), which talks about waiting for a webpage to load completely. You may need to use selenium – inspectorG4dget Sep 24 '12 at 10:59
1

This solution is fairly cross-platform, but if you're trying to show a bit of a web page open in a desktop with menu/toolbars etc... it's not what you want.

You could use SeleniumHQ to automate a browser of your choice, have that browser render the page, then get the complete image of the rendered page - ie, not just a screenshot of the portion of the page that's displayed on screen. You could then crop that accordingly.

Jon Clements
  • 138,671
  • 33
  • 247
  • 280