3

I'm using phantomjs to take a snapshot of a webpage (for example: http://www.baixaki.com.br/ ) using python.

here is the code:

from selenium import webdriver
driver = webdriver.PhantomJS() # or add to your PATH

driver.get('http://www.baixaki.com.br/')
driver.save_screenshot('screen6.png') # save a screenshot to disk

The input is a url, the output is an image. The problem is that the snap shot generated is narrow and long: narrow and long snapshot

I want to capture only what fits in the page without scrolling and full width. For example, something like this: enter image description here

  • I'm looking for a generic solution not a specific one.

Would appreciate your help here.

omer bach
  • 2,345
  • 5
  • 30
  • 46
  • http://stackoverflow.com/questions/11917042/how-to-render-part-of-a-page-with-phantomjs –  Sep 29 '16 at 15:53
  • This post is not in python and is directed to a specific web page using an id of a specific element. I'm looking for a generic solution to take a snapshot using python for a certain part of the page... – omer bach Sep 29 '16 at 16:01
  • Hmm... not as helpful as I thought it would be because Python's more different than I expected (thought making the jump would be easier); have you tried the webdriver set_window_size function? E.g., driver.set_window_size(1400,1000) –  Sep 29 '16 at 16:37
  • Hi, first I appreciate your help. Thanks. I've tried that with no success.... – omer bach Sep 29 '16 at 16:52

1 Answers1

4

You could try cropping the image (I'm using Python 3.5 so you may have to adjust to use StringIO if you're in Python 2.X):

from io import BytesIO
from selenium import webdriver
from PIL import Image

if __name__ == '__main__':
    driver = webdriver.PhantomJS('C:<Path to Phantomjs>')
    driver.set_window_size(1400, 1000)
    driver.get('http://www.baixaki.com.br/')
    driver.save_screenshot('screen6.png')
    screen = driver.get_screenshot_as_png()

    # Crop image
    box = (0, 0, 1366, 728)
    im = Image.open(BytesIO(screen))
    region = im.crop(box)
    region.save('screen7.png', 'PNG', optimize=True, quality=95)

credit where credit is due: https://gist.github.com/jsok/9502024

  • Thank you. Looks very promising. – omer bach Sep 30 '16 at 07:39
  • This will crop the top of the image, but in my case the page has a pop-up dialog that is in the **middle** of that insanely tall screenshot, so I'd have to crop twice: once for the top (to get the page header), and once for the middle (to get the dialog in the middle). I need a way for selenium to respect set_window_size()'s **height**. It wants to screencap the entire scrollable height, instead of the "viewing rectangle". – Donn Lee Jan 09 '17 at 00:13