基于d创建文件夹

2024-10-03 21:29:21 发布

您现在位置:Python中文网/ 问答频道 /正文

我是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

如您所见,它只创建文件。我要它按日期保存在文件夹里。我怎么才能做到呢。 谢谢你


Tags: 代码文件夹is网站stepdriverscraperprint
2条回答

您希望将数据保存在何处?根目录/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还提供小时、分钟和秒,以备您需要:

^{pr2}$
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")

相关问题 更多 >