【问题标题】:Take a screenshot from a website from commandline or with python从命令行或使用 python 从网站截取屏幕截图
【发布时间】:2013-04-27 00:26:18
【问题描述】:

我将从这个页面截取屏幕截图:http://books.google.de/books?id=gikDAAAAMBAJ&pg=PA1&img=1&w=2500 或保存它输出的图像。

但我找不到方法。使用 wget/curl 我得到一个“不可用的错误”,还有其他工具,如 webkit2png/wkhtmltoimage/wkhtmltopng。

有没有一种干净的方法可以用 python 或从命令行来做?

最好的问候!

【问题讨论】:

  • 据我了解,他们不从网页截取屏幕截图,只从打开的窗口截取。但我的计划是在不自己打开网址的情况下做到这一点。有大约 1000 张图像要保存。仅限某些书籍的封面。

标签: python command-line web screenshot


【解决方案1】:

如果你愿意,你可以使用 ghost.py。 https://github.com/jeanphix/Ghost.py

这是一个如何使用它的示例。

from ghost import Ghost
ghost = Ghost(wait_timeout=4)
ghost.open('http://www.google.com')
ghost.capture_to('screen_shot.png')

最后一行将图像保存在当前目录中。

希望对你有帮助

【讨论】:

  • 不错的一个。看起来不错,但我不想安装 Qt。 ://
【解决方案2】:

我很难让 Ghost 在无头 Centos 虚拟机上始终如一地截取屏幕截图。 Selenium 和 PhantomJS 为我工作:

from selenium import webdriver
br = webdriver.PhantomJS()
br.get('http://www.stackoverflow.com')
br.save_screenshot('screenshot.png')
br.quit

【讨论】:

  • 运行时出现此错误:Traceback (most recent call last): File "C:\bunker\Lib\site-packages\custom_selenium.py", line 2, in <module> br = webdriver.PhantomJS() File "C:\bunker\Lib\site-packages\selenium\webdriver\phantomjs\webdriver.py", line 49, in __init__ service_args=service_args,log_path=service_log_path) TypeError: __init__() got an unexpected keyword argument 'log_path'
  • 嗯,不确定,但我想知道如果您编辑 webdriver.py init 并删除 log_path 参数会发生什么
【解决方案3】:

有时您需要额外的 http 标头(例如 User-Agent)才能使下载工作。在 python 2.7 中,您可以:

import urllib2
request = urllib2.Request(
    r'http://books.google.de/books?id=gikDAAAAMBAJ&pg=PA1&img=1&w=2500',
    headers={'User-Agent':'Mozilla/5.0 (X11; U; Linux i686) Gecko/20071127 firefox/2.0.0.11'})
page = urllib2.urlopen(request)

with open('somefile.png','wb') as f:
    f.write(page.read())

或者您可以查看在 wget 或 curl 中添加 http 标头的参数。

【讨论】:

  • 但它不会生成捕获网站的图像。图像将被破坏。
  • @SarvagyaPant 我运行了这个脚本并验证下载了一个完整的图像。这花了我不到一分钟的时间。在提出未经证实的声明之前,您能否做一些工作。
  • 只有当url 为direct link to image 时才会生成正确的图像。对于其他基于 html 的网页,这将不起作用。此外,如果url保证是图片,可以直接使用urllib.urlretrieve。
  • 它适用于任何单一资源,例如图像、网页、mp3、pdf 等...它不会跟随链接或构建复合网页,但这不是用户追求。他向我们展示了一张图片的网址,并说他想要一张图片的“截图”。但“截图”只是图像文件本身。有多种下载网络内容的方法 - 我的示例是一种完全正常的接受方式。
猜你喜欢
  • 1970-01-01
  • 2010-11-14
  • 1970-01-01
  • 1970-01-01
  • 2012-10-20
  • 1970-01-01
  • 2016-06-06
  • 1970-01-01
  • 2017-05-05
相关资源
最近更新 更多