使用selenium和phantomjs的脚本可以检查大约20个动态页面,并在没有屏幕截图部分的情况下警告我发生更改时可以快速运行,但是当我想要获取页面的屏幕截图时,大约需要1-2分钟来警告我并获取屏幕截图.有没有更好,更快的方法来使用python截取页面特定部分的屏幕截图?
这是我用于屏幕截图的代码.
from selenium import webdriver
from PIL import Image
fox = webdriver.Firefox()
fox.get('https://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
SOLVED:
The problem is not about selenium module, either screenshot. It is
about phantomjs, after I start using chromedriver it is very fast and more
efficent.SOLUTION UPDATE:
The problem with phantomjs is disabling images. When I use
--load-images=no
I face with the memory leak issue and scripts gets really slower, without it there
is no problem.
解决方法:
您可以通过在内存中裁剪屏幕截图来节省一些时间,而无需先将其保存到文件中:
import StringIO
from selenium import webdriver
from PIL import Image
driver = webdriver.Firefox()
driver.get('https://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')
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。