我有一个包含多个用户ID和推文ID的文件。我试图使用这些信息检索推文 当我尝试检索推文时,我遇到了问题。当twitter发现暂停帐户时,python脚本崩溃了。我得到的错误是:
AttributeError: 'NoneType' object has no attribute 'findNext'
因为我还是Python的新手,我不知道如何处理这个问题。我希望脚本继续检索推文,即使它找到任何暂停的帐户。
暂停帐户的示例是 following
的推文示例我用来检索推文的代码如下:
def get_tweet(user_id, tweet_id):
"""fetch the tweet from given user_id and tweet_id
returns tweet text if found, otherwise returns Not Found
"""
url = TWITTER_URL + user_id + "/status/" + tweet_id
url = url.replace("\n", "")
print(url);
tweet = 'Not Found'
try:
response = urllib2.urlopen(url)
html = response.read()
soup = BeautifulSoup(html)
#extrat the paragraph that contains the tweet
tweet_paragrapgh = soup.find("div", 'original-tweet',{"data-user-id": user_id, "data-tweet-id": tweet_id}).findNext('p','js-tweet-text')
#strip off the html tag and get the tweet text
#print(tweet_paragrapgh);
tweet = tweet_paragrapgh.text
print (tweet);
except urllib2.HTTPError as e:
print
print "HTTP ERROR response code ", e.code, " for user id: ", user_id, " tweet id: ", tweet_id
return tweet
except urllib2.URLError as e:
print
print'Error reaching to server for ', "user id: ", user_id, " tweet id: ", tweet_id
print 'Reason: ', e.reason
return tweet
return tweet
提前感谢
答案 0 :(得分:1)
通过urllib2
+ BeautifulSoup
解析Twitter页面非常痛苦,因为构建页面时涉及很多动态javascript逻辑,AJAX
调用。
具体而言,您实际使用urllib2
的网页不包含original-tweet
,没有data-tweet-id
属性的元素,所有data-user-id
}属性为空。
使用Twitter API
而不是重新发明轮子。
有多个python twitter API客户端可供选择:
希望有所帮助。