今天尝试用Cron来执行每天晚上24点前的流量检测脚本。但奇怪的是,直接在macOS的终端运行没有问题的程序,如果用Cron来运行,就会报错,先后报过print和文件的url错误。
print(time.strftime("%Y-%m-%d %H:%M:%S ", time.localtime()) + arg)
UnicodeEncodeError: ‘ascii’ codec can’t encode characters in position 21-23: ordinal not in range(128)
data_file.write(str(page_text))
UnicodeEncodeError: ‘ascii’ codec can’t encode characters in position 218-222: ordinal not in range(128)
查了半天文件,说法多种多样。最后解决问题的方法却很简单。
打开文件的时候指定编码:
fp= open(‘test.txt’, ‘w’, encoding=’utf-8′)
运行python文件的时候:
PYTHONIOENCODING=utf-8 /usr/local/bin/python3 abc.py
于是搞定!这样每天可以安排电脑晚上自动运行爬数了,哈哈
—
Regards,
Li Zhen