【发布时间】: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 但它只有一次并且 cpu 消耗也增加了很多。这种情况肯定不正常。我认为问题出在 Selenium 屏幕截图部分,因为我关注它并看到它在文件夹中在一秒钟内裁剪了完整图像。
标签: python performance selenium phantomjs screenshot