Issue
I have pulled a few things from other answers today (this for instance: href="https://stackoverflow.com/questions/34961910/open-a-browser-page-and-take-screenshot-every-n-hour-in-python-3/68189559#68189559">open a browser page and take screenshot every n hour in python 3)
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
import time
browser = webdriver.Firefox()
browser.implicitly_wait(30)
browser.get('https://weather.com/en-AU/weather/today/l/ASXX0023:1:AS?Goto=Redirected')
time.sleep(10)
browser.save_screenshot('screen_shot.png')
browser.close()
this solution is working perfectly except I'm not sure how to execute in crontab.
i tried this after typing crontab -e then:
*/30 * * * * export DISPLAY=:0 /usr/local/bin/python3.9 /Users/path/script.py >> /path/screenshot.png
and it opens the firefox window, but the screenshot is Zero Bytes.. so it's close to what I want, but not quite there.
I tried a few other ways too - with script.sh - though I'm not to sure how to get that working either.
Also - it'd be good to add the time and date to the screenshot, so any help there is a blessing.
could you offer any guidance? Thanks!
Solution
The cron
job will start in your home directory, and writes the screenshot to the current directory.
The cron
job you have will also write the standard output from Python to a misleadingly named PNG file which will probably be empty. Probably this is the file you have been examining.
Probably restructure to switch to a different directory (or modify the Python script to read an output file name as its command-line argument) and write the script's output to a differently named file, also then including standard error. Furthermore, the DISPLAY
variable does nothing useful on a Mac, so probably drop it.
*/30 * * * * cd code; /usr/local/bin/python3.9 /Users/path/script.py >> screenshot_$(date +\%F).log 2>&1
This also illustrates how to create a new log file for each separate date. The requirement to backslash the percent sign in crontab
is a common trip-up.
If instead, or as well, you would like the Python script to generate a unique file name for each invocation, try something like
from datetime import datetime
...
browser.save_screenshot(
'screen_shot_' + datetime.now().strftime('%F_%T') + '.png')
This will generate a file like screen_shot_2021-06-30_10:26:26.png
; maybe play around with the argument to strftime()
if you would like a different date or time format.
Answered By - tripleee Answer Checked By - Timothy Miller (WPSolving Admin)