Reputation: 61
I am a newbie in python and building a scraper using webdriver. I am trying to take screenshots from a website. Its taking the screenshot fine but saving it in the root folder. My code is below
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
As you can see, its only creating files. I want it to save it in folder by date. How can I achieve that. Thank you
Upvotes: 0
Views: 2300
Reputation: 1
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")
Upvotes: 0
Reputation: 311
Where do you want to save the data? root/savedir? In any case, the reason you're saving the screenshot in root folder is "./" in third row of your code. You can try to specify the entire path:
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
also provides hours, minutes and seconds in case you need them:
savedir = time.strftime('%Y%m%d%H%M%S')
#returns string of YearMonthDayHourMinutesSeconds
Upvotes: 1