Better way to take screenshot of a url in Python

試著忘記壹切 提交于 2019-12-21 17:45:32

问题


Problem Description

Currently working on a project which requires me to take browse a url and take a screenshot of the webpage.

After looking various resources i found 3 ways to do so.I will be mentioning all 3 methods iam currently using.

Method - 1 : PhantomJS

from selenium import webdriver
import time
import sys

print 'Without Headless'
_start = time.time()
br = webdriver.PhantomJS()
br.get('http://' + sys.argv[1])
br.save_screenshot('screenshot-phantom.png')
br.quit
_end = time.time()
print 'Total time for non-headless {}'.format(_end - _start)

Method-2 : Headless Browser

from selenium import webdriver
from selenium.webdriver.chrome.options import Options

print 'Headless'
_start = time.time()
options = Options()
options.add_argument("--headless") # Runs Chrome in headless mode.
options.add_argument('--no-sandbox') # # Bypass OS security model
options.add_argument('start-maximized')
options.add_argument('disable-infobars')
options.add_argument("--disable-extensions")
driver = webdriver.Chrome(chrome_options=options, executable_path='/usr/bin/chromedriver')
driver.get('http://' + sys.argv[1])
driver.save_screenshot('screenshot-headless.png')
driver.quit()
_end = time.time()
print 'Total time for headless {}'.format(_end - _start)

Method - 3 :PyQT

import argparse
import sys
import logging
import sys
import time
import os

import urlparse
from selenium import webdriver
from PyQt4.QtCore import *
from PyQt4.QtGui import *
from PyQt4.QtWebKit import *

class Screenshot(QWebView):
    def __init__(self):
        self.app = QApplication(sys.argv)
        QWebView.__init__(self)
        self._loaded = False
        self.loadFinished.connect(self._loadFinished)

    def capture(self, url, output_file):
        _logger.info('Received url {}'.format(url))
        _start = time.time()
        try:
            #Check for http/https
            if url[0:3] == 'http' or url[0:4] == 'https':
                self.url = url
            else:
                url = 'http://' + url
            self.load(QUrl(url))
            self.wait_load(url)
            # set to webpage size
            frame = self.page().mainFrame()
            self.page().setViewportSize(frame.contentsSize())
            # render image
            image = QImage(self.page().viewportSize(), QImage.Format_ARGB32)
            painter = QPainter(image)
            frame.render(painter)
            painter.end()
            _logger.info('Saving screenshot {} for {}'.format(output_file,url))
            image.save(os.path.join(os.path.dirname(os.path.realpath(__file__)),'data',output_file))
        except Exception as e:
            _logger.error('Error in capturing screenshot {} - {}'.format(url,e))
        _end = time.time()
        _logger.info('Time took for processing url {} - {}'.format(url,_end - _start))

    def wait_load(self,url,delay=1,retry_count=60):
        # process app events until page loaded
        while not self._loaded and retry_count:
            _logger.info('wait_load for url {} retry_count {}'.format(url,retry_count))
            self.app.processEvents()
            time.sleep(delay)
            retry_count -=1
        _logger.info('wait_load for url {} expired'.format(url))
        self._loaded = False

    def _loadFinished(self, result):
        self._loaded = True

Issue Faced:

These 3 methods while using,all of them are getting stuck due to one or other error.One such issue faced is asked here Error Question on Stackoverflow. So out of these 3 methods to take screenshot of a webpage in Python,which is effecient and will work on large scale deployment.

来源:https://stackoverflow.com/questions/51000899/better-way-to-take-screenshot-of-a-url-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!