python-3.x - 在 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 .. 对我没有用,所以我认为我做错了什么。在网上真的找不到任何可以解释的东西。
解决方案
首先,您的程序需要工作。我没看。希望它确实有效。然而,与其试图让它工作并让 crontab 正确并让 Python crontab 入口程序正确,不如一次做一个。
- 我尝试了python-crontab 演示,它只是评估 bash 语句
echo hello_world
。我将用户从 更改root
为mslinn
。您也应该从这个开始,使用适当的用户 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 中进行了正确的输入。
因为 crontab 不在交互式 shell 中运行,所以输出在您的 shell 中不可见。我建议您的程序将输出写入文件。如果您坚持将输出发送到 STDOUT 或 STDERR,您可以通过电子邮件发送 crontab 输出(但所有 crontab 条目都会通过电子邮件发送其输出!)要通过电子邮件发送输出,请将其放在 crontab: 的顶部
MAILTO=email@example.com
,根据文档。从命令行测试您的程序。
现在才尝试从 crontab 运行您的程序。
推荐阅读
- kubernetes - 无法使用 kubectl cp 命令将数据从 POD 复制到本地
- python - 如何合并值
- python - 我第一次使用 python 进行网络抓取失败,通过 python 为每个人书
- azure - Azure 组件的自定义角色
- git - Git .gitignore 命令
- node.js - 强制停止范围外的生成器功能
- radio-button - 使用标签选择的单选按钮未显示为选中状态
- cygwin - 有什么方法可以告诉 make 在发生故障时打印更好的诊断信息?
- javascript - 验证 MIME 类型的 Javascript
- firebase - Firebase 电话身份验证问题