0

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

ScareCrow
  • 19
  • 8
  • Related reading: [How can I create a directory if it does not exist?](https://stackoverflow.com/q/273192/953482), [Convert datetime object to a String of date only in Python](https://stackoverflow.com/q/10624937/953482) – Kevin Dec 01 '17 at 13:41
  • 1
    Possible duplicate of [python create directory structure based on the date](https://stackoverflow.com/questions/34411061/python-create-directory-structure-based-on-the-date) – Bill the Lizard Dec 01 '17 at 13:41
  • Please [edit the question](https://stackoverflow.com/posts/47594644/edit) to show examples of how the filenames should look like. For example is it the current date or some other date? – Martin Evans Dec 01 '17 at 13:48

2 Answers2

1

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
zck
  • 176
  • 3
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")
Sean
  • 1
  • 1
    Hi @Sean, could you please add more detail to your answer? There's already a very similar answer, could you explain in what your is different? – toti08 Sep 24 '18 at 09:11