如何使用python将网页保存为图像

时间:2010-11-03 21:39:33

标签: python web screenshot

我正在使用python创建网站的“收藏夹”部分。我想做的部分是抓取一个图像放在他们的链接旁边。因此,过程将是用户输入URL,然后我抓住该页面的屏幕截图并将其显示在链接旁边。够容易吗?

我目前已经下载了pywebshot,它在本地设备上的终端上运行良好。但是,当我把它放在服务器上时,我得到一个带有以下回溯的分段错误:

/usr/lib/pymodules/python2.6/gtk-2.0/gtk/__init__.py:57: GtkWarning: could not open display
  warnings.warn(str(e), _gtk.Warning)
./pywebshot.py:16: Warning: invalid (NULL) pointer instance
  self.parent = gtk.Window(gtk.WINDOW_TOPLEVEL)
./pywebshot.py:16: Warning: g_signal_connect_data: assertion `G_TYPE_CHECK_INSTANCE (instance)' failed
  self.parent = gtk.Window(gtk.WINDOW_TOPLEVEL)
./pywebshot.py:49: GtkWarning: Screen for GtkWindow not set; you must always set
a screen for a GtkWindow before using the window
  self.parent.show_all()
./pywebshot.py:49: GtkWarning: gdk_screen_get_default_colormap: assertion `GDK_IS_SCREEN (screen)' failed
  self.parent.show_all()
./pywebshot.py:49: GtkWarning: gdk_colormap_get_visual: assertion `GDK_IS_COLORMAP (colormap)' failed
  self.parent.show_all()
./pywebshot.py:49: GtkWarning: gdk_screen_get_root_window: assertion `GDK_IS_SCREEN (screen)' failed
  self.parent.show_all()
./pywebshot.py:49: GtkWarning: gdk_window_new: assertion `GDK_IS_WINDOW (parent)' failed
  self.parent.show_all()
Segmentation fault

我知道有些事情不能在pts环境中运行,但老实说现在有点超出我的意义。如果我需要以某种方式假装我的pts连接是tty,我可以试试。但在这一点上,我甚至不确定发生了什么,我承认这有点过头了。任何帮助将不胜感激。

此外,如果有一个Web服务,我可以传递一个URL并接收一个图像,这也可以。我没和pywebshot的想法结婚。

我知道我所在的服务器正在运行X并安装了所有必需的python模块。

提前致谢。

4 个答案:

答案 0 :(得分:2)

我发现websnapr.com这是一项网络服务,只需一点点工作即可为您提供图像。

import subprocess
subprocess.Popen(['wget', '-O', MYFILENAME+'.png', 'http://images.websnapr.com/?url='+MYURL+'&size=s&nocache=82']).wait()

很容易就是馅饼。

答案 1 :(得分:1)

from selenium import webdriver    
from xvfbwrapper import Xvfb
d=Xvfb(width=400,height=400)
d.start()
browser=webdriver.Firefox()
url="http://stackoverflow.com/questions/4091940/how-to-save-web-page-as-image-using-python"
browser.get(url)
destination="screenshot_filename.jpg"
if browser.save_screenshot(destination):
    print "File saved in the destination filename"
browser.quit()

答案 2 :(得分:0)

您可以使用iMacros for Firefox(开源)from the command line并使用以下take browser screenshot宏命令保存图像。

URL GOTO=http://www.yoursite.com
SAVEAS TYPE=PNG FOLDER=* FILE=My_Screenshot.png 

这适用于任何网站。

答案 3 :(得分:0)

我猜,服务器没有X服务器,对吗?

您可能需要运行无头X服务器才能实现此功能。

相关问题