python - 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()
解决方案
尝试代替
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
推荐阅读
- bash - 使用 shell 将值写入特定的行和列
- apache-spark - Maven SL4J 多重绑定,之前的解决方案失败
- laravel - 雄辩的分页两个关系合并
- python - 如何在 python 中使用 os.walk 更改根文件夹和所有子目录中的 ext?
- c# - 是否可以在 AWS 中托管 *CONSOLE* 应用程序
- ssl - 防止 Tomcat 发送标头“连接:关闭”
- javascript - 添加 ngx-charts 的依赖以集成组合图
- android - Android 上的弹出窗口
- vba - 在vba中获取所有带括号“<”和“>”的子字符串
- android - 通知不适用于 Api 27(8.1.0)