首页 > 解决方案 > Trying to take and save a screenshot of a specific element (selenium, python, chromedriver)

问题描述

I am trying to take and save a screenshot of the image+comment block that can be seen by navigating to https://www.instagram.com/p/B9MjyquAfkE/. Below is a testable piece of my code.

I am getting an error:
article.screenshot_as_png('article.png') TypeError: 'bytes' object is not callable

It seems that the code is able to find article, but is having an issue with the screenshot. I am also trying to specify a certain location where I want to save my screenshot on my computer.

from selenium import webdriver
import time

class bot:

    def __init__(self):
        self.driver = webdriver.Chrome("path to chrome driver here")

    def screenShot(self):
        driver = self.driver
        driver.get("https://www.instagram.com/p/B9MjyquAfkE/")
        time.sleep(2)
        #find post+comments block on page
        article = driver.find_elements_by_xpath('//div[@role="dialog" or @id="react-root"]//article')[-1]
        #take screenshot of the post+comments block 
        article.screenshot_as_png('article.png')

if __name__ == "__main__":
    bot = bot()
    bot.screenShot()

标签: pythonseleniumselenium-chromedriver

解决方案


尝试代替

article.screenshot_as_png('article.png')

这个:

screenshot_as_bytes = article.screenshot_as_png
with open('article.png', 'wb') as f:
    f.write(screenshot_as_bytes)

解释:

article.screenshot_as_png已经是以字节为单位的屏幕截图,您需要做的就是保存它。如果您像这样调用它,article.screenshot_as_png()那么将尝试对字节执行,因此会出现错误:TypeError: 'bytes' object is not callable


推荐阅读