关于python:从控制台工作的Selenium脚本,不在CRON中工作 – Geckodriver错误

Selenium script working from console, not working in CRON - Geckodriver error

我有从sh文件运行的Selenium脚本。当我从控制台运行sh文件时,它工作得非常好,但从cron作业运行的相同文件失败。

SH文件:

1
2
3
4
5
#!/bin/sh

export DISPLAY=:10
cd /home/user
python3 selenium.py > /home/user/selenium.log 2>&1

我得到的错误是众所周知的:

Traceback (most recent call last): File
"/usr/local/lib/python3.5/dist-packages/selenium/webdriver/common/service.py",
line 74, in start
stdout=self.log_file, stderr=self.log_file) File"/usr/lib/python3.5/subprocess.py", line 947, in init
restore_signals, start_new_session) File"/usr/lib/python3.5/subprocess.py", line 1551, in _execute_child
raise child_exception_type(errno_num, err_msg) FileNotFoundError: [Errno 2] No such file or directory: 'geckodriver'

During handling of the above exception, another exception occurred:

Traceback (most recent call last): File"so_login.py", line 12, in
setUp
self.driver = webdriver.Firefox() File"/usr/local/lib/python3.5/dist-packages/selenium/webdriver/firefox/webdriver.py",
line 142, in init
self.service.start() File"/usr/local/lib/python3.5/dist-packages/selenium/webdriver/common/service.py",
line 81, in start
os.path.basename(self.path), self.start_error_message) selenium.common.exceptions.WebDriverException: Message: 'geckodriver'
executable needs to be in PATH.

我在控制台中也有这个错误,但是我通过安装geckoDriver并将其移动到/usr/local/bin解决了这个问题,并且它在控制台中工作正常,但是为什么它不在cron中工作呢?


考虑使用pyvirtualdisplay为您管理窗口会话

用PIP安装

1
$ pip install pyvirtualdisplay

然后在代码中添加如下内容:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
from pyvirtualdisplay import Display


def main():
    # Display creates a virtual frame buffer and manages it for you
    with Display(visible=False, size=(1200, 1500)):
        # Run the test of your code here

    # When your code is finished and exits the with block, the with
    # context manager cleans up the virtual display for you


if __name__ =="__main__":
    main()