【问题标题】:How to exclude retweet when scraping tweet with tweepy使用 tweepy 抓取推文时如何排除转推
【发布时间】:2020-07-10 11:11:39
【问题描述】:

我想用 tweepy 从 twitter 上抓取数据,但我不想在其中包含转推。怎么做?

这是我的代码:

import tweepy
import csv

consumer_key = 'xx'
consumer_secret = 'xx'
access_token = 'xx'
access_token_secret = 'xx'

auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_token_secret)
api = tweepy.API(auth,wait_on_rate_limit=True)

csvpefile = open ('netflix.csv', 'a')
csvWriter = csv.writer(csvpefile)


for tweet in tweepy.Cursor(api.search,
                       q=["netflix"], 
                       lang="id",
                       since="2020-07-8", 
                       tweet_mode = 'extended', 
                       trucated='false').items(200):

print(tweet.created_at, tweet.id, tweet.full_text)
csvWriter.writerow([tweet.created_at, tweet.id, tweet.full_text.encode('utf-8')])

我试过了

                    count=None,
                    since_id=None,
                    max_id=None,
                    trim_user=False,
                    exclude_replies=False,
                    contributor_details=False,
                    include_entities=True):
                  

q=["netflix -filter:retweets"]

在 api.search 中,但还是不行

【问题讨论】:

    标签: python twitter tweepy


    【解决方案1】:

    通过添加快速检查以查看推文文本字符串是否以 rt @ 开头,您应该能够阻止转推出现在您的 csv 文档中。

    import tweepy
    import csv
    
    consumer_key = 'xx'
    consumer_secret = 'xx'
    access_token = 'xx'
    access_token_secret = 'xx'
    
    auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
    auth.set_access_token(access_token, access_token_secret)
    api = tweepy.API(auth,wait_on_rate_limit=True)
    
    csvpefile = open ('netflix.csv', 'a')
    csvWriter = csv.writer(csvpefile)
    
    
    for tweet in tweepy.Cursor(api.search,
                           q=["netflix"], 
                           lang="id",
                           since="2020-07-8", 
                           tweet_mode = 'extended', 
                           trucated='false').items(200):
    
    # could go without this variable it just makes it easier
    tweettext = str(tweet.full_text.lower().encode('ascii',errors='ignore'))
    
    # check if the tweet starts with the format for a retweet
    if tweettext.startswith("rt @") == False:
        csvWriter.writerow([tweet.created_at, tweet.id, tweet.full_text.encode('utf-8')])
    

    【讨论】:

    • 如果这仍然不起作用,请将检查行编辑为 if tweettext.startswith("rt @") == False and hasattr(tweet, 'retweeted_status') == False:
    【解决方案2】:

    要在搜索中排除转推,请尝试:

    q=["netflix -filter:retweets"]
    

    注意:使用 tweepy 不是“抓取”。您正在使用公共 API。

    【讨论】:

    • 它不起作用,RT 仍然存在于我的 csv 文件中。它在爬行吗?
    猜你喜欢
    • 2016-12-16
    • 2021-10-03
    • 1970-01-01
    • 2017-05-01
    • 1970-01-01
    • 2016-06-26
    • 2020-09-07
    • 2015-04-27
    • 2019-06-02
    相关资源
    最近更新 更多