为什么crontab无法启动safari驱动

问题描述 投票:0回答:1

昨晚,我正在尝试使用selenium和python来制作一个脚本来填充我的大学提供的网站中的体温

但是当我想用crontab自动执行脚本时,总是报这样的错误

  File "/Users/clay_codes1024/PythonProject/FillTemperature.py", line 20, in <module>
    driver = webdriver.Safari()
  File "/usr/local/lib/python3.9/site-packages/selenium/webdriver/safari/webdriver.py", line 57, in __init__
    self.service.start()
  File "/usr/local/lib/python3.9/site-packages/selenium/webdriver/common/service.py", line 98, in start
    self.assert_process_still_running()
  File "/usr/local/lib/python3.9/site-packages/selenium/webdriver/common/service.py", line 109, in assert_process_still_running
    raise WebDriverException(
selenium.common.exceptions.WebDriverException: Message: Service /usr/bin/safaridriver unexpectedly exited. Status code was: 1

这是我的Python代码

from selenium import webdriver
import time

account = ''
password = ''
temperature = ''

driver = webdriver.Safari()

driver.get('')

driver.find_element_by_id("username").send_keys(account)

time.sleep(2)

driver.find_element_by_id("password").click()

driver.find_element_by_id("password").send_keys(password)

driver.find_element_by_id("passbutton").click()

driver.find_element_by_xpath('/html/body/div/div/div/div/div[1]/div[2]/div/form/div[18]/div[1]/div/div[2]/div/div/input').clear()
time.sleep(2)
driver.find_element_by_xpath('/html/body/div/div/div/div/div[1]/div[2]/div/form/div[18]/div[1]/div/div[2]/div/div/input').send_keys(temperature)
time.sleep(2)

# use javascript to click the log in button
js = 'document.getElementById("post").click();'
driver.execute_script(js)
time.sleep(5)

driver.quit()

我做了什么:

1. Give the full disk access to Python3, crontab, terminal

2. Use shell script to execute the python script like this
echo 'password' | sudo -S /usr/local/bin/python3 /Users/clay_codes1024/PythonProject/FillTemperature.py

3. Turn on the 'Allow remote automation' in safari

以上都不起作用!

所以请帮助我

非常感谢!!!!!!

python selenium cron
1个回答
0
投票

Safari 没有无头模式,并且 cron 通常无法访问显示器,因此您将很难让浏览器或 safari 驱动程序以这种方式启动。

我通过使用用户登录时运行的 LaunchAgent 来解决这个问题 - 对于这些东西有一个 简单的备忘单 ,但你只需要创建一个基本的 plist 文件来运行你的脚本,比如这个每五分钟运行一次:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple Computer//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
    <key>Label</key>
    <string>com.somedomain.your-script-name.plist</string>
    <key>KeepAlive</key>
    <false/>
    <key>ProgramArguments</key>
    <array>
        <string>/path/to/your/script.sh</string>
    </array>
    <key>StartInterval</key>
    <integer>300</integer>
</dict>
</plist>

假设它保存在

~/Library/LaunchAgents/com.somedomain.your-script-name.plist
,然后通过运行
id
命令找到你的uid,然后运行:

cd ~/Library/LaunchAgents
launchctl bootstrap gui/<uid> com.somedomain.your-script-name.plist
launchctl enable gui/<uid>/com.somedomain.your-script-name.plist
© www.soinside.com 2019 - 2024. All rights reserved.