A D
A D

Reputation: 135

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()

Upvotes: 3

Views: 1507

Answers (1)

Trapli
Trapli

Reputation: 1597

Try instead of

article.screenshot_as_png('article.png')

This:

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

Explanation:

article.screenshot_as_png is already the screenshot in bytes, all you need to do is to save it. If you call it like article.screenshot_as_png() then the execution will be attempted on the bytes, hence the error: TypeError: 'bytes' object is not callable

Upvotes: 6

Related Questions