gpt4 book ai didi

python - 将 selenium python 保存到 s3

转载 作者:行者123 更新时间:2023-12-02 09:08:14 25 4
gpt4 key购买 nike

我正在尝试确定将 selenium 屏幕截图保存到 S3 的最 Pythonic 方法。我真的很想避免将 selenium 屏幕截图写入磁盘,然后加载并保存到 S3。但是我认为不可能将 Selenium 屏幕截图保存为变量。下面是我到目前为止想出的功能。我可以使用 boto 将其直接保存到该位置吗?

def screenshot(request):
conn = S3Connection('########', '########')
bucket = conn.get_bucket('bucket')
k = Key(bucket)
k.key = 'lab3'
driver = webdriver.PhantomJS() # or add to your PATH
driver.set_window_size(1024, 768) # optional
driver.get(request)
driver.save_screenshot(request + '_toS3.png') # would rather save to s3

注意:使用 django 在 Apache Web 服务器上运行

最佳答案

import boto3
import io
from selenium import webdriver


S3_Client = boto3.client('s3')
chrome_path = 'path/to/chromedriver'
driver = webdriver.Chrome(options=options, executable_path=chrome_path)

driver.get('www.example.com')
screenshot = driver.get_screenshot_as_png()
in_memory_file = io.BytesIO(screenshot)
S3_Client.upload_fileobj(in_memory_file, 'mybucket', 'screenshot.png')

更新了代码以响应 Addison:

import boto3
import io
from selenium import webdriver
from selenium.webdriver.common.keys import Keys

driver = webdriver.Chrome(executable_path='path/to/chromedriver')
s3 = boto3.client('s3')

driver.get('https://www.example.com')

# The driver will scroll to the bottom. This is a bug that has yet to be fixed
# This brings the driver back up to the top of the page
driver.find_element_by_tag_name('body').send_keys(Keys.CONTROL + Keys.HOME)

with io.BytesIO(driver.get_screenshot_as_png()) as f:
s3.upload_fileobj(f, 'mybucket', 'screenshot.png')

# optional
driver.close()

关于python - 将 selenium python 保存到 s3,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39009998/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com