繁体   English   中英

发送推文时Crontab出现Unicode错误

[英]Crontab has unicode error when sending tweet

我目前正在运行python脚本,以检测包含产品的网站的json对象中的更改。

当我在ubuntu服务器上手动运行它时,它工作正常(发送鸣叫),但是当它与crontab一起运行时,会出现以下错误:

UnicodeEncodeError: 'ascii' codec can't encode character u'\\xa0' in position 20: ordinal not in range(128)

这是代码。 基本上,我正在比较json文件的不同版本,看是否有区别。 如果有所不同,请发送一条推文。

#!/usr/bin/env python3
import twitter
import requests
from jsondiff import diff
from classes.logger import Logger
from classes.proxies import Proxy
import webbrowser
import time
import json

log = Logger().log

class Cactus:
    proxy = Proxy()
    def __init__(self):
        self.url = 'http://api.bigcartel.com/cactusplantfleamarket/products.json'
        self.front = 'http://www.cactusplantfleamarket.bigcartel.com'
        self.api = twitter.Api(consumer_key='xxx',
                  consumer_secret='xxx',
                  access_token_key='xxx',
                  access_token_secret='xxx')

def scrape(self):

    with open('cactus.txt') as oldjson:
        old = json.load(oldjson);


    current_proxy = self.proxy.getProxy()[self.proxy.countProxy()]
    session = requests.session()
    resp = session.get(self.url, proxies=current_proxy).json()

    with open('cactus.txt', 'w') as outfile:
        json.dump(resp, outfile)

    if diff(resp, old) != {}:

        if len(resp) == 0:
            curr_time = time.strftime("%d %b %H:%M:%S", time.gmtime())
            self.api.PostUpdate('Website Updated at ' + curr_time )
        else:
            for item in range(len(resp)):
                try:
                    self.tweet(resp[item])
                except Exception as e:
                    print(e)


    def tweet(self, item):
        print(item['name'])
        curr_time = time.strftime("%d %b %H:%M:%S", time.gmtime())
        url = self.front + item['url']
        shorturl = self.goo_shorten_url(url)['id']
        self.api.PostUpdate('CPFM: ' + item['name'] + ' - ' + curr_time + ' ' + shorturl)

    def goo_shorten_url(self, url):
        API_KEY = 'xxxx'
        post_url = 'https://www.googleapis.com/urlshortener/v1/url?key={}'.format(API_KEY)
        payload = {'longUrl': url}
        headers = {'content-type': 'application/json'}
        r = requests.post(post_url, data=json.dumps(payload), headers=headers)
        return r.json()

我们在聊天中进行了一些侦查,发现该脚本是意外地使用Python 2而不是Python 3运行的(线索是u'\\xa0'上的u前缀)。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM