如何使用python-webkit2png同时截取多个屏幕截图?

4 投票
3 回答
10004 浏览
提问于 2025-04-15 22:12

我有成千上万的网址,来自很多不同的主机,我需要对它们进行截图。

我可以在命令行中很好地使用这个库,但我该如何把它集成到我的代码中,以便可以同时截图多个呢?

我觉得这可能和xvfb有关,就像这个问题的回答里提到的:如何结束通过Python启动的无头X服务器? 但我不太确定具体是怎么回事。

3 个回答

0

可能是这样的(没测试过):

from webkit2png import WebkitRenderer, init_qtgui
from PyQt4.QtCore import QTimer

def renderer_func():   
    renderer = WebkitRenderer()
    renderer.width = 800
    renderer.height = 600
    renderer.timeout = 10
    renderer.wait = 1
    renderer.format = "png"
    renderer.grabWholeWindow = False

    outfile = open("stackoverflow.png", "w")
    renderer.render_to_file(url="http://stackoverflow.com", file=outfile)
    outfile.close()

app = init_qtgui()
QTimer.singleShot(0, renderer_func)
sys.exit(app.exec_())

这段代码是直接从webkit2png.py的源代码抄过来的,毫不掩饰。

1

我用 subprocess 这个工具来调用 webkit2png,这个工具是通过 python-webkit2png 安装的,运行得很顺利。

def scrape_url(url, outpath):
    """
    Requires webkit2png to be on the path
    """
    subprocess.call(["webkit2png", "-o", outpath, "-g", "1000", "1260",
                     "-t", "30", url])

def scrape_list_urls(list_url_out_name, outdir):
    """
    list_url_out_name is a list of tuples: (url, name)
    where name.png will be the image's name
    """
    count = 0
    for url, name in list_url_out_name:
        print count
        count += 1
        outpath = outdir + name + '.png'
        scrape_url(url, outpath)
2

在这里,我使用了一个参数来传递一个.txt文件的位置,这个文件里包含了一些网站的列表(每个网站之间用换行符分隔),第二个参数是输出PNG文件的位置。

https://gist.github.com/deadstar1/e8d30102afbaefec531d6708f761e104 感谢 @paljenczy

撰写回答