Trying to take and save a screenshot of a specific element (selenium, python, chromedriver)

十年热恋 提交于 2020-04-16 02:51:06

问题


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


回答1:


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 try to 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



来源:https://stackoverflow.com/questions/60999624/trying-to-take-and-save-a-screenshot-of-a-specific-element-selenium-python-ch

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!