AttributeError:'NoneType'对象没有属性'findNext'>>在检索推文时

时间:2014-05-21 21:22:43

标签: python twitter beautifulsoup tweets

我有一个包含多个用户ID和推文ID的文件。我试图使用这些信息检索推文 当我尝试检索推文时,我遇到了问题。当twitter发现暂停帐户时,python脚本崩溃了。我得到的错误是:

AttributeError: 'NoneType' object has no attribute 'findNext'

因为我还是Python的新手,我不知道如何处理这个问题。我希望脚本继续检索推文,即使它找到任何暂停的帐户。

暂停帐户的示例是 following

retrieved successfully

的推文示例

我用来检索推文的代码如下:

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

提前感谢

1 个答案:

答案 0 :(得分:1)

通过urllib2 + BeautifulSoup解析Twitter页面非常痛苦,因为构建页面时涉及很多动态javascript逻辑,AJAX调用。

具体而言,您实际使用urllib2的网页不包含original-tweet,没有data-tweet-id属性的元素,所有data-user-id }属性为空。

使用Twitter API而不是重新发明轮子。

有多个python twitter API客户端可供选择:

希望有所帮助。