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

2024-05-15 03:19:15 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在使用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连接是tty,我可以试试。但在这一点上,我甚至不知道发生了什么,我承认这有点过头了。任何帮助都将不胜感激。

另外,如果有一个web服务,我可以传递一个url并接收一个图像,那也可以。我不同意pywebshot的想法。

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

提前谢谢。


Tags: pyselfgtkisshowallscreenparent
3条回答

我找到了websnapr.com这是一个web服务,它只需做一点工作就可以为您提供图像。

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

像馅饼一样容易。

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()

让我猜猜,服务器没有X服务器,对吧?

您可能需要运行一个无头的X服务器才能使其正常工作。

相关问题 更多 >

    热门问题