我在使用 Tweepy 和不同于 ASCII 的字符时遇到问题。我尝试了多种不同的方法,但每种方法在终端中都有不同的错误。
所以,首先我完成 Twitter 要求的所有舞蹈并导入我需要的东西:
from lxml import html
import requests
from random import randint
import tweepy, sys, time
import requests
import unicodedata
consumer_key="x"
consumer_secret="y"
access_token="z"
access_token_secret="w"
auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_token_secret)
api = tweepy.API(auth)
然后,我去一个网站寻找要发推文的句子。
page = requests.get("www.webpage.com")
poemT = html.fromstring(page.text)
phrases = poemT.xpath('//div[@class="mainData"]/text()')
尝试转换句子时,我找不到适合函数 api.update_satus() 的格式,并且每次尝试时都会出现以下错误消息。
尝试 1:
tuite = phrases.pop(0)
api.update_status(tuite)
错误:
UnicodeEncodeError: 'ascii' codec can't encode character u'\xe9' in position 0: ordinal not in range(128)
有了这个错误,我找到了 this , this , this和其他一些人在下面提出解决方案。但是,我在尝试打印句子时没有遇到任何问题。我想这就是它没有解决我的问题的原因。
尝试 2
tuite = phrases.pop(0).encode('utf-8')
api.update_status(tuite)
错误:
tweepy.error.TweepError: Failed to send request: Headers indicate a formencoded body but body was not decodable.
由于这个错误,我找不到任何相关的东西。但我只是尝试将 ASCII 中的句子转换为 this问题说。但我仍然遇到错误。
尝试 3
title = phrases.pop(0)
tuite = unicodedata.normalize('NFKD', title).encode('ascii','ignore')
api.update_status(tuite)
错误:
tweepy.error.TweepError: [{u'message': u'media_ids parameter is invalid.', u'code': 44}]
我还找到了this问题,但它与媒体更新有关。
最后
我找到了 this git 上的讨论表明我的问题是一个错误(?),将在 Tweepy 中修复。
有什么想法吗?如果我可以将文本转换为 api.update_status() 接受的格式,我会很高兴。
请您参考如下方法:
我刚刚在这个链接中找到了答案:
Traceback when updating status on twitter via Tweepy
原来我应该像下面这样调用更新函数:
api.update_status(status=tuite)
