Cannot get #reboot Cron job to run Python script - python

I have a cron job that loads a Python script on reboot but it will just not work.
I have checked the Python script and that works fine from CLi.
The .py basically loads a browser to Google and then sends it to full screen.
(It actually loads another website and enters login details also, but removed for obvious reasons)
Been at this for weeks now and driving me crazy, any ideas?
Raspberry Pi running Raspbian.
$crontab -e
#reboot DISPLAY=:0 python /prtgboot.py
prtgboot.py
'#'!/usr/bin/env python
import commands
import time
webbrowser = "iceweasel"
pgrepcmd = "pgrep %s " % (webbrowser)
process = commands.getoutput(pgrepcmd)
if process == "":
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver import ActionChains
browser = webdriver.Firefox()
actions = ActionChains(browser)
browser.get('http://google.co.uk')
elemFullscreen = browser.find_element_by_tag_name('html')
time.sleep(30)
elemFullscreen.send_keys (Keys.F11)
exit()
else:
exit()

Ok, so Petesh was correct. It was #reboot not working correctly.
Changed the cron to * * * * * so my script runs every minute. Normally bad practice, but already setup script to end if browser already running. Working a treat now.
On a positive note, if the browser crashes it will start again for me :)

Related

Cron SyntaxError with Selenium Python Script

I'm a beginner trying to write a small Python script that I will run through Cron, but I'm getting a Syntax Error from my Cron output log about the program, although the script works fine running through Terminal.
File "/home/pi/Selenium.py", line 19
clickinput = driver.find_element_by_link_text(f"{date}- File")
^
SyntaxError: invalid syntax
I tried looking up how to do this, and one person with a similar issue changed Cron to run as Bash instead of sh, but when I added SHELL = /bin/bash to the Cron file, nothing happened, and I got the same error. Additionally, when I change the f-string into a non f-string, a "selenium module not found" error gets thrown instead.
Any help figuring out the cause of the error would be appreciated!
Cron command:
PATH = /home/pi/.local/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/s$
SHELL = /bin/bash
20 18 * * * /home/pi/Selenium.py > /home/pi/Desktop/backdown.log 2>&1
20 18 * * * env > /home/pi/Desktop/env.output 2>&1
Here is my Python script (minus private info)
#!/usr/bin/env python
import time
from datetime import datetime
from selenium import webdriver
driver = webdriver.Chrome("/usr/lib/chromium-browser/chromedriver")
driver.get("website");
searchinput = driver.find_element_by_name('mail')
searchinput.send_keys("email")
searchinput = driver.find_element_by_name("pass")
searchinput.send_keys("password")
searchinput.submit()
date = datetime.today().strftime("%m/%d")
if date.find("0") == 0:
date = date.lstrip("0")
clickinput = driver.find_element_by_link_text(f"{date}- File")
clickinput.click()
(This is my first time posting, so sorry if it's bad)

Python script not executed from crontab

I am not able to execute the below attached python script via crontab. When I run script directly from CLI it works just fine, I see just a quick action how browser is opened, everything is setup and then browser closes. But when run in crontab, nothing happens.
Crontab entry:
* * * * * /full/path/to/script.py
I also tried :
* * * * * /usr/bib/python /full/path/to/script.py
SCRIPT:
#!/usr/bin/python
from selenium import webdriver
from selenium.webdriver.support.ui import Select
browser = webdriver.Chrome(executable_path="/usr/local/bin/chromedriver")
#open website
browser.get("http:website.php")
# find element in dropdown
Select(browser.find_element_by_name("ma")).select_by_value("817")
# confirm by clicking button
element = browser.find_element_by_xpath("/html/body/form/table/tbody/tr[2]/td[3]/input")
element.click()
# select dropdown
Select(browser.find_element_by_name("status")).select_by_value("11")
#confirm dropdown
submit = browser.find_element_by_xpath("/html/body/form/table[3]/tbody/tr/td/input")
submit.click()
browser.close()
/var/log/syslog:
May 4 11:34:01 pavol-Vostro-15-3568 CRON[11685]: (root) CMD (/full/path/to/script.py)
I faced a problem similar to yours. Your job might be failing because it requires an X session since you're trying to open a web browser. You should put export DISPLAY=:0; after the schedule in your cronjob, as in
* * * * * export DISPLAY=:0; /usr/bib/python /full/path/to/script.py
If this doesn't work, you could try replacing :0 with the output of echo $DISPLAY in a graphical terminal.

I can't get this to run on start Up

I have this python code, which when I run it, it works and brings me to YouTube. I'm trying to get it so every time I boot up the raspberry pi it will run my python code and take me straight to YouTube. The rc.local file runs but it says
could not locate runnable browser
Here is my python program
import webbrowser, os, sys
url = "http://www.youtube.com"
chrome_path = '/usr/lib/chromium-browser/chromium-browser'
def main():
webbrowser.get(chrome_path).open(url)
main()
Here is my rc.local file
python /home/pi/browserOpen/OpenBrowser.py &
exit 0
Try to change your main() function like this:
def main():
webbrowser.register('chrome', None, webbrowser.BackgroundBrowser(chrome_path), 1)
webbrowser.get('chrome')
webbrowser.open(url, new=2)
and set chrome_path to "/usr/bin/chromium-browser/chromium-browser"
UPDATE:
Try creating .sh file in the same directory as your .py file, put /yourpath/bin/yourscript.sh & in rc.local and this code:
#!/bin/sh
sleep 10
python scriptname.py
in yourscript.sh file.
Original answer from here

Py program gives an error if I dont open it with interactive shell

I 've a porgram called searchMachine.py that if I run it straight from IDLE (F5..)it works just fine, but If I run it by just clicking on searchMachine.py it works untill somepoint and then I get an error. See below.
Thanks for any input you could give me.
By the way, any idea how I can make this chrome work in silent? for example minimized?
from selenium import webdriver
from selenium.webdriver.support.ui import Select
print('Please type the machine name.')
machinename = input()
print('')
print('Thank you.')
print('')
print('Results will show below.')
print('')
path_to_chromedriver = 'C:\python34\chromedriver\chromedriver.exe' # change path as needed
browser = webdriver.Chrome(executable_path = path_to_chromedriver)
url = 'http://app.corp'
browser.get(url)
browser.find_element_by_xpath("/html/body/div[4]/form/table[1]/tbody/tr/td[5]/input[1]").send_keys(machinename)
browser.find_element_by_css_selector('input[type=\"submit\"]').click() # working to press submit
xpath = '/html/body/div[4]/form/center[2]/table/thead'
for i in browser.find_elements_by_xpath(xpath):
print (i.text)
xpath = '/html/body/div[4]/form/center[2]/table/tbody/tr'
for i in browser.find_elements_by_xpath(xpath):
print (i.text)
browser.close()
import os
os.system("c:/code/close_chrome_driver.bat")
error is:
The error occurs because the unicode character ▾ or U+25BE BLACK DOWN-POINTING SMALL TRIANGLE cannot be written into Windows console window, as it does not have a match in the CP850 character set as used by your Windows console.
Now, Python croaks loudly when it cannot print the correct value. You could set the PYTHONIOENCODING environment variable to say cp850:ignore which would make the Python process ignore errors; or you can print to stderr instead of stdout, which would use the backslashescape error handling.

Closing all the opened chrome windows using selenium - python - osx

I have to download some files from a website, I'm using Python - Selenium - Chrome - Osx.
I have his code so far:
lnk = "www.foobar.com"
CHROMEDRIVER=webdriver.Chrome()
options = webdriver.ChromeOptions()
profile = {"plugins.plugins_list": [{"enabled":False, "name":"Chrome PDF Viewer"}],
"download.default_directory" : TEMP_DOWNLOAD}
options.add_experimental_option("prefs",profile)
driver = webdriver.Chrome(chrome_options = options)
driver.get(lnk)
while True:
if filter(os.path.isfile, glob.glob(TEMP_DOWNLOAD+'/*.crdownload')):
pass
else:
break
driver.quit()
This code starts the download of the file, waits the end of the download and then closes the webdriver.
Everything is working properly except that it opens 2 Chrome windows, one to open the link and the other to download the file, and the quit() method closes only the latter.
Is there a way to kill all the windows opened by Selenium (I'm trying to avoid firing a terminal command to kill the processes brute force)?
EDIT:
as Mukesh Takhtani said in comment in my code the problem is a pointless webdriver instance.
Use this. This I used for Firefox. You can use this for Chrome. Call kill_waste() in your python code and it would kill idle useless Chrome. Please note that this would work for OSX or FreeBSD. For Linux distros you would have to change the way you are going to use grep and cut
import commands
def kill_waste():
(_,firefox_processes) = commands.getstatusoutput("ps -ax | grep '/usr/local/bin/firefox -foreground' | cut -c1-24")
sleep(0.5)
firefox_processes = firefox_processes.splitlines()
for pid in firefox_processes:
values = pid.split()
time_value = values[3].split(':')
if ((values[2] == 'I' or values[2] == 'I+') and time_value[0] == '1') or time_value[0] == '2':
commands.getstatusoutput("kill -9 " + values[0])

Categories