我是python中的新手并使用webdriver构建一个scraper。我试图从网站截取屏幕截图。它的截图很好,但保存在根文件夹中。我的代码在
之下print ("step is === "+str(scrollStep))
for i in range(1, max_sreenshots):
driver.save_screenshot("./screenshot_"+str(i)+".png")
driver.execute_script("window.scrollTo("+str(scrollStart)+", "+str(scrollEnd)+");")
scrollStart = scrollStart + scrollStep
scrollEnd = scrollEnd + scrollStep
如您所见,它只创建文件。我希望它按日期保存在文件夹中。我怎样才能做到这一点。 谢谢
答案 0 :(得分:0)
您想在哪里保存数据?根/ SaveDir可以?在任何情况下,您在根文件夹中保存屏幕截图的原因是" ./"在你的代码的第三行。您可以尝试指定整个路径:
import os
import time
#in case you want to save to the location of script you're running
curdir = os.path.dirname(__file__)
#name the savedir, might add screenshots/ before the datetime for clarity
savedir = time.strftime('%Y%m%d')
#the full savepath is then:
savepath = os.path.join(curdir + '/', savedir)
#in case the folder has not been created yet / except already exists error:
try:
os.makedirs(savepath)
except:
pass
#now join the path in save_screenshot:
driver.save_screenshot(savepath + "/screenshot_"+str(i)+".png")
time.strftime
还可以提供小时,分钟和秒钟,以备不时之需:
savedir = time.strftime('%Y%m%d%H%M%S')
#returns string of YearMonthDayHourMinutesSeconds
答案 1 :(得分:0)
from datetime import datetime, timedelta
# Try this
# save screenshot into desired path
# declare variables Year, Month, Day
today = datetime.now()
# format is up to you
Day = today.strftime("%d.%m")
Month = today.strftime("%b")
Year = today.strftime("%Y")
# Copy and paste path, add in double backslashes
# single forward slashes for the time variables
# and lastly, enter the screenshot name
browser.save_screenshot("C:\\XYZ\\ABC\\" + Year + "/" + Month + "/" + Day + "/Screenshot.png")