调度程序生成 python 脚本 运行 但不生成 csv 文件

Scheduler makes a python script run but doesn't produce a csv file

我在 python 中编写了一个脚本,用于从网页上抓取一些链接并将它们写入 csv 文件。当 运行 来自 IDE.

时,我的脚本以正确的方式执行此操作

当我 运行 同样使用 windows task scheduler 时,我可以看到 command prompt 弹出,脚本 运行s 也在那里打印结果,但我任务完成后没有得到任何 csv 文件。

我是不是漏掉了什么?

当脚本是 运行 通过 .bat 文件从 windows task scheduler 获取 csv 文件时,我应该做哪些可能的更改?

.bat 包含:

@echo off
"C:\Users\WCS\AppData\Local\Programs\Python\Python36-32\python.exe" "C:\Users\WCS\AppData\Local\Programs\Python\Python36-32\examplescript.py"

examplescript.py 包含:

import csv
import requests
from urllib.parse import urljoin
from bs4 import BeautifulSoup

url = "https://www.janglo.net/component/option,com_sobi2/"

def get_info(link):
    res = requests.get(url)
    soup = BeautifulSoup(res.text,"lxml")
    for items in soup.select("#sobi2CatListSymbols .sobi2SubcatsListItems a[title]"):
        if items.text=="Tutors":
            ilink = f"{urljoin(url,items.get('href'))}"
    return ilink

def get_links(tlink):
    linklist = []
    res = requests.get(tlink)
    soup = BeautifulSoup(res.text,"lxml")
    for item in soup.select(".sobi2ItemTitle a"):
        linklist.append(urljoin(url,item.get("href")))
    return linklist

if __name__ == '__main__':
    with open("task_scheduler.csv","a",newline="") as infile:
        writer = csv.writer(infile)
        item = get_info(url)
        for nlink in get_links(item):
            print(nlink)
            writer.writerow([nlink])

我已经在下面明确指定了“.bat”文件的位置:

"C:\Users\WCS\AppData\Local\Programs\Python\Python36-32\test_schedule.bat"

您的代码写入当前工作目录,因为它打开了一个没有路径的文件名。 .bat 文件的位置无法确定代码的 当前工作目录 运行。

您没有指定工作目录;我希望使用调度程序中的 Start in 字段进行设置,因此文件是在 default location%Windir%\System32\.[=16 中创建的=]

Start in 字段中为要创建的 CSV 文件设置一个目录,让您的批处理脚本使用 cd 将当前工作目录移动到正确的位置,或者在打开文件时使用绝对路径。

例如,如果您的批处理脚本首先 运行s cd /d %~dp0 然后工作目录更改为批处理脚本的目录,并且 Python 中的相对路径被解析为那个位置。