首页 > 解决方案 > 在 VScode 中创建非常简单的 cronjob 来执行 scraper.py

问题描述

我正在尝试学习如何创建一个 cronjob,但是有很多方法可以做到这一点......似乎没有一个对我有用。

我有一个名为 Cron.py 的文件:

from crontab import CronTab
cron = CronTab()
my_cron= CronTab(user='ttmz')
job = my_cron.new(command='python beddenscraper.py')
job.minute.every(1)

cron.write()

这应该触发beddenscraper.py:

import requests
from bs4 import BeautifulSoup
import pandas as pd

scraped_data=[]
details= {}


page=requests.get('https://www.swisssense.nl/bedden')
soup = BeautifulSoup(page.content, 'html.parser')

products = soup.find_all("a", class_="product-item-link")
prices = soup.find_all("span", class_="price")
images = soup.find_all("img", class_="product-image-photo")



bed_data = soup.find_all("li", attrs={"class", "item product product-item"})# total number of bedden

for bed in bed_data:
    bed_naam = bed.find("a", class_="product-item-link").getText()
    bed_price = bed.find(
        "span", class_="price"
    ).getText()  # print(bed_naam.text, bed_price.text)
    scraped_data.append(
        {"bed_naam": bed_naam.strip(), "bed_price": bed_price.strip()}
    )

dataFrame = pd.DataFrame.from_dict(scraped_data)
dataFrame.to_csv('swisssense.csv', index=False)

所以:不幸的是我收到了大量的错误信息。还有一些人在终端中使用 Crontab-e,或者 crontab -1 .. 对我没有用,所以我认为我做错了什么。在网上真的找不到任何可以解释的东西。

标签: python-3.xcron

解决方案


首先,您的程序需要工作。我没看。希望它确实有效。然而,与其试图让它工作并让 crontab 正确并让 Python crontab 入口程序正确,不如一次做一个。

  1. 我尝试了python-crontab 演示,它只是评估 bash 语句echo hello_world。我将用户从 更改rootmslinn。您也应该从这个开始,使用适当的用户 ID。
$ pip install python-crontab 

$ python <<EOF
> from crontab import CronTab
> cron = CronTab(user='mslinn')
> job = cron.new(command='echo hello_world')
> job.minute.every(1)
> cron.write()
> EOF

$ crontab -l | tail -n 1
* * * * * echo hello_world

crontab -l 表明在 usermslinn的 crontab 中进行了正确的输入。

  1. 因为 crontab 不在交互式 shell 中运行,所以输出在您的 shell 中不可见。我建议您的程序将输出写入文件。如果您坚持将输出发送到 STDOUT 或 STDERR,您可以通过电子邮件发送 crontab 输出(但所有 crontab 条目都会通过电子邮件发送其输出!)要通过电子邮件发送输出,请将其放在 crontab: 的顶部MAILTO=email@example.com根据文档

  2. 从命令行测试您的程序。

  3. 现在才尝试从 crontab 运行您的程序。


推荐阅读