在使用 Twitter 搜索 API 获取推文时,我们可能会遇到重复获取相同推文的问题。这可能会导致我们在处理推文时出现数据丢失或重复的情况。为了解决这个问题,我们需要找到一种方法来避免获取重复的推文。
一种解决方法是使用 Twitter 搜索 API 中的 since_id
参数。since_id
参数可以让我们指定一个推文 ID,并仅获取该推文 ID 之后发布的推文。通过这种方式,我们可以避免获取重复的推文。
下面是一个使用 since_id
参数获取最新推文 ID 的 Python 代码示例:
import twitter
class Test():
def __init__(self):
self.t_auth()
self.hashtag = ['justinbieber']
self.tweets_1 = []
self.ids_1 = []
self.created_at_1 = []
self.tweet_text_1 = []
self.last_id_1 = ""
self.page_1 = 1
self.tweets_2 = []
self.ids_2 = []
self.created_at_2 = []
self.tweet_text_2 = []
self.last_id_2 = ""
self.page_2 = 1
for i in range(1, 16):
self.tweets_1.extend(self.api.GetSearch(self.hashtag, per_page=100, since_id=self.last_id_1, page=self.page_1))
self.page_1 += 1
print(len(self.tweets_1))
for t in self.tweets_1:
self.ids_1.insert(0, t.id)
self.created_at_1.insert(0, t.created_at)
self.tweet_text_1.insert(0, t.text)
self.last_id_1 = t.id
self.last_id_2 = self.last_id_1
for i in range(1, 16):
self.tweets_2.extend(self.api.GetSearch(self.hashtag, per_page=100, since_id=self.last_id_2, page=self.page_2))
self.page_2 += 1
print(len(self.tweets_2))
for t in self.tweets_2:
self.ids_2.insert(0, t.id)
self.created_at_2.insert(0, t.created_at)
self.tweet_text_2.insert(0, t.text)
self.last_id_2 = t.id
print('Total number of tweets in test 1: ', len(self.tweets_1))
print('Last id of test 1: ', self.last_id_1)
print('Total number of tweets in test 2: ', len(self.tweets_2))
print('Last id of test 2: ', self.last_id_2)
print('##################################')
print('#############OVERLAPING###########')
ids_overlap = set(self.ids_1).intersection(self.ids_2)
tweets_text_overlap = set(self.tweet_text_1).intersection(self.tweet_text_2)
created_at_overlap = set(self.created_at_1).intersection(self.created_at_2)
print('Ids: ', len(ids_overlap))
print('Text: ', len(tweets_text_overlap))
print('Created_at: ', len(created_at_overlap))
print(ids_overlap)
print(tweets_text_overlap)
print(created_at_overlap)
def t_auth(self):
consumer_key = "xxx"
consumer_secret = "xxx"
access_key = "xxx"
access_secret = "xxx"
self.api = twitter.Api(consumer_key, consumer_secret, access_key, access_secret)
self.api.VerifyCredentials()
return self.api
if __name__ == "__main__":
Test()
在上面的代码中,我们在第 27 行使用 since_id
参数来指定一个推文 ID,并仅获取该推文 ID 之后发布的推文。通过这种方式,我们可以避免获取重复的推文。
另外,我们还可以使用 max_id
参数来指定一个推文 ID,并仅获取该推文 ID 之前的推文。这也可以用来避免获取重复的推文。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。