最新消息:20210816 当前crifan.com域名已被污染,为防止失联,请关注(页面右下角的)公众号

【已解决】Selenium中实现给浏览器截图并保存

selenium crifan 5605浏览 0评论

折腾:

【记录】尝试用Python操作PhantomJS+Selenium去模拟购物操作

期间,

selenium screenshot python

python – Webdriver Screenshot – Stack Overflow

Selenium take screenshot – Python Tutorial

然后用:

driver.save_screenshot(“befrugalHomepage.png”)

即可保存截图:

再去试试另外的:

Take screenshot of a webpage using Selenium & Python – IdiotInside.com

driver.get_screenshot_as_file

然后试了试:

driver.save_screenshot(“befrugalHomepage.png”)

# driver.get_screenshot_as_png(“befrugalHomepage1.png”)

driver.get_screenshot_as_file(“befrugalHomepage2.png”)

是可以生成图片的:

对应的三个函数,通过查看源码:

/usr/local/lib/python2.7/site-packages/selenium/webdriver/remote/webdriver.py

得知:

def get_screenshot_as_file(self, filename):

    “””

    Saves a screenshot of the current window to a PNG image file. Returns

       False if there is any IOError, else returns True. Use full paths in

       your filename.

    :Args:

     – filename: The full path you wish to save your screenshot to. This

       should end with a `.png` extension.

    :Usage:

        driver.get_screenshot_as_file(‘/Screenshots/foo.png’)

    “””

    if not filename.lower().endswith(‘.png’):

        warnings.warn(“name used for saved screenshot does not match file “

                      “type. It should end with a `.png` extension”, UserWarning)

    png = self.get_screenshot_as_png()

    try:

        with open(filename, ‘wb’) as f:

            f.write(png)

    except IOError:

        return False

    finally:

        del png

    return True

def save_screenshot(self, filename):

    “””

    Saves a screenshot of the current window to a PNG image file. Returns

       False if there is any IOError, else returns True. Use full paths in

       your filename.

    :Args:

     – filename: The full path you wish to save your screenshot to. This

       should end with a `.png` extension.

    :Usage:

        driver.save_screenshot(‘/Screenshots/foo.png’)

    “””

    return self.get_screenshot_as_file(filename)

def get_screenshot_as_png(self):

    “””

    Gets the screenshot of the current window as a binary data.

    :Usage:

        driver.get_screenshot_as_png()

    “””

    return base64.b64decode(self.get_screenshot_as_base64().encode(‘ascii’))

【总结】

selenium中截图的话,有两个函数都可以:

  • driver.save_screenshot(“screenshot_filename.png”)

    • 内部就是调用get_screenshot_as_file实现的

  • driver.get_screenshot_as_file(“screenshot_filename.png”)

    • get_screenshot_as_file内部又是调用get_screenshot_as_png得到png截图的

转载请注明:在路上 » 【已解决】Selenium中实现给浏览器截图并保存

发表我的评论
取消评论

表情

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址
83 queries in 0.202 seconds, using 22.12MB memory