【问题标题】:Selenium Screenshot Works Slow (Python)Selenium 屏幕截图运行缓慢(Python)
【发布时间】:2016-04-15 20:07:01
【问题描述】:

带有 selenium 和 phantomjs 的脚本可以检查大约 20 个动态页面并在有更改时警告我,无需屏幕截图部分即可快速运行,但是当我想要获取页面的屏幕截图时,大约需要 1-2 分钟来警告我并获取截屏。有没有更好更快的方法用 python 截取页面的特定部分?

这是我用于截图的代码。

from selenium import webdriver
from PIL import Image

fox = webdriver.Firefox()
fox.get('http://stackoverflow.com/')

# now that we have the preliminary stuff out of the way time to get that image :D
element = fox.find_element_by_id('hlogo') # find part of the page you want image of
location = element.location
size = element.size
fox.save_screenshot('screenshot.png') # saves screenshot of entire page
fox.quit()

im = Image.open('screenshot.png') # uses PIL library to open image in memory

left = location['x']
top = location['y']
right = location['x'] + size['width']
bottom = location['y'] + size['height']


im = im.crop((left, top, right, bottom)) # defines crop points
im.save('screenshot.png') # saves new cropped image

已解决:

问题不在于 selenium 模块,无论是屏幕截图。这是 关于 phantomjs,在我开始使用 chromedriver 之后,它非常快而且更多 有效。

解决方案更新:

phantomjs 的问题是禁用图像。当我使用 --load-images=no 我面临内存泄漏问题,脚本变得非常慢,没有它 没问题。

【问题讨论】:

  • 你确定你的代码的哪一部分花费的时间太长了吗? Selenium 截图,还是 PIL 裁剪图?你确定当时的记忆发生了什么吗?当时的 CPU 资源情况如何?
  • 是的,我做到了。对于 phantomjs 内存增加到 3gb 并卡在 3gb 直到我关闭它,一旦我在活动监视器中看到 5gb 但它只有一次并且 c​​pu 消耗也增加了很多。这种情况肯定不正常。我认为问题出在 Selenium 屏幕截图部分,因为我关注它并看到它在文件夹中在一秒钟内裁剪了完整图像。

标签: python performance selenium phantomjs screenshot


【解决方案1】:

您可以通过在内存中裁剪屏幕截图而不先将其保存到文件来节省一些时间:

import StringIO
from selenium import webdriver
from PIL import Image

driver = webdriver.Firefox()
driver.get('http://stackoverflow.com')
element = driver.find_element_by_id('hlogo')

crop_points = driver.execute_script("""
    var r = arguments[0].getBoundingClientRect();
    return [r.left, r.top, r.left + r.width, r.top + r.height];
    """, element)

with Image.open(StringIO.StringIO(driver.get_screenshot_as_png())) as img :
    with img.crop(crop_points) as imgsub :
        imgsub.save(logo.png', 'PNG')

【讨论】:

  • 感谢您的回答,但最快的部分是裁剪。我真的不知道为什么,但是 phantomjs 会消耗内存,这是不正常的并且工作速度非常慢。我正在使用带有 4gb ram、i5 和 phantomjs 的 osx 内存消耗可高达 3gb。怎么可能?
  • Chrome 怎么样?它一样糟糕吗?可能存在内存泄漏,但没有可重现的示例,很难说。
  • 你不会相信我,但即使我使用它来加载图像,它也只有 35mb。相同的脚本,相同的条件。我真的不明白 phantomjs 有什么问题。它是最新的。所以问题不在于脚本或硒,问题完全在于 phantomjs。好吧,我在 osx 上,所以我不能让 chromedriver 无头,这就是我必须使用 phantomjs 的原因。
  • 另外,使用 firefox 消耗的内存约为 400mb。也不能使用无头。
  • 我只能推荐你使用 Chrome 而不是 PhantomJS。如果你真的不想要这个窗口,那么你应该在屏幕外启动浏览器来隐藏它。
猜你喜欢
  • 2013-01-24
  • 2012-12-05
  • 1970-01-01
  • 1970-01-01
  • 2011-10-13
  • 2016-02-12
  • 1970-01-01
  • 2019-02-08
  • 2014-08-25
相关资源
最近更新 更多