如何使用python-webkit2png同时拍摄许多屏幕快照?

2024-04-29 12:19:18 发布

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

我有成千上万的网址从许多主机我需要截图。

我可以从命令行使用lib fine,但如何将其集成到代码中以便同时拍摄多个屏幕快照?

我认为这和xvfb有关,就像这个问题的答案一样:How to kill headless X server started via Python?但是我不确定具体是什么。


Tags: to答案代码命令行server屏幕lib快照
3条回答

可能是这样的(未经测试):

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

这是不知羞耻地从source code of webkit2png.py上撕下来的。

我用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)

在这里,我使用了一个参数来传递.txt的位置,它包含一个站点列表(以换行分隔),以及输出PNG文件位置的第二个参数。

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

相关问题 更多 >