selenium 当脚本通过cron运行时,Python/Selify会失败,但当脚本手动运行时,它可以正常运行

gpfsuwkq  于 2022-11-10  发布在  Python
关注(0)|答案(1)|浏览(199)

在运行Ubuntu Server22.04的Raspberry PI 4上使用Selify运行一个Python脚本。铬浏览器ChromeDriver V 103.0.5060.53(当前稳定通过https://chromedriver.chromium.org/)
当我在终端中运行该脚本时,一切都按预期运行,但是,当该脚本通过cron作业执行时,该脚本失败并显示以下错误:

Traceback (most recent call last):
  File "/home/ubuntu/code.py", line 59, in <module>
    driver = webdriver.Chrome(service=Service('/usr/lib/chromium-browser/chromedriver'), options=chrome_options)
  File "/home/ubuntu/.local/lib/python3.10/site-packages/selenium/webdriver/chrome/webdriver.py", line 70, in __init__
    super(WebDriver, self).__init__(DesiredCapabilities.CHROME['browserName'], "goog",
  File "/home/ubuntu/.local/lib/python3.10/site-packages/selenium/webdriver/chromium/webdriver.py", line 89, in __init__
    self.service.start()
  File "/home/ubuntu/.local/lib/python3.10/site-packages/selenium/webdriver/common/service.py", line 98, in start
    self.assert_process_still_running()
  File "/home/ubuntu/.local/lib/python3.10/site-packages/selenium/webdriver/common/service.py", line 110, in assert_process_still_running
    raise WebDriverException(
selenium.common.exceptions.WebDriverException: Message: Service /usr/lib/chromium-browser/chromedriver unexpectedly exited. Status code was: 1

下面是我配置驱动程序的方式:

chrome_options = Options()
chrome_options.add_argument('--disable-gpu')
chrome_options.add_argument('--headless')
chrome_options.add_argument('start_maximized')
chrome_options.add_experimental_option('excludeSwitches', ['enable-logging'])
chrome_options.add_argument("disable-infobars")
driver = webdriver.Chrome(service=Service('/usr/lib/chromium-browser/chromedriver'), options=chrome_options)

找不到状态代码为1或ASSERT_PROCESS_STY_RUNNING的任何故障排除,因此,如果有任何帮助,我们将不胜感激:)

von4xj4u

von4xj4u1#

我也有同样的问题。我发现,如果我更新CRONTAB,则下一次运行将成功,但后续运行将失败,状态为1。
因此,我创建了一个脚本来自动更新我的cron作业将运行的时间,这很麻烦,但它很有帮助。

import subprocess # needed for the subprocess.run function
import random # need for the choice function

def listToString (listA,delim = " "):
    result = ""
    for i in listA:
        result = result + str(i) + delim
    return result

# Run crontab

cronProcess = subprocess.run(["crontab", "-l" ], capture_output=True,text=True)

# Set the output from the stdout then split the string by newline

cronList = cronProcess.stdout.split("\n")

# Filter for the job that we want, that is, filter out comments and blank lines

# Return a tuple of the index and the job we want to change the run time for

jobToFind = "nameOfJobToEdit"
cronJobTuple = [(index, job) for index, job in enumerate(cronList) if len(job) > 0 and job[0] != "#"  and job.find(jobToFind) >= 0  ][0]

# Save the index and job info

cronJobIndex = int(cronJobTuple[0])
cronJobStr = cronJobTuple[1]

# Split the cronjob so that the date/times are separate

cronJobList = cronJobStr.split(" ", 5)

# Get the minute/hour values from the cronjob

minuteJobLastRan =  int(cronJobList[0])
hourJobLastRan   =  int(cronJobList[1])

# Remove the previous minute the job last ran

minsInHour = list(range(0,60))
minsInHour.pop(minuteJobLastRan)
minuteToRunJobList = minsInHour

# Remove the previous hour the job last ran

hoursInDay = list(range(0,23))
hoursInDay.pop(hourJobLastRan)
hourToRunJobList = hoursInDay

# Select a random minute/hour to run the new job

cronJobList[0] = random.choice(minuteToRunJobList)
cronJobList[1] = random.choice(hourToRunJobList)

# Convert the job back to a string

modifiedCronJobStr = listToString(cronJobList)

# Update the cronTab with the modified job

cronList[cronJobIndex] = modifiedCronJobStr

# Convert the entire cronTab back to a string

cronStr = listToString(cronList,delim="\n")

# Save the string to file

# open text file

file_name = "tmpCronFile.txt"
text_file = open(file_name, "w")

# write string to file

n = text_file.write(cronStr)    

# close file

text_file.close()
print("Status code of write is [{}]".format(n))

# Update crontab

subprocess.run(["crontab", file_name ], capture_output=True,text=True)

# Delete temp file

subprocess.run(["rm", file_name ], capture_output=True,text=True

然后,我将其创建为cronTab的一个条目,并且它每天午夜更新cronTab


# m  h   dom  mon dow  command

0 0 * * * python $HOME/cronExecutionTimeRandomiser/cronExecutionTimeRandomiser.py > $HOME/log/cronExecutionTimeRandomiser`date +\%Y\%m\%d\%H\%M\%S`.log 2>&1

相关问题