omer bach
omer bach

Reputation: 2405

How to take a partial web snapshot in phantomjs using python?

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

Would appreciate your help here.

Upvotes: 3

Views: 1049

Answers (1)

user2096803
user2096803

Reputation:

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

Upvotes: 4

Related Questions