【问题标题】:Is there any way to get the number of comments on a tweet using python?有什么方法可以使用 python 获取推文的评论数量?
【发布时间】:2018-03-05 20:54:28
【问题描述】:

我正在使用 Tweepy,但似乎没有办法从用户那里获取特定推文上的 cmets 数量。我可以使用tweet.favorite_counttweet.retweet_count 来获得收藏和转发,但我正在寻找一种方法来获取该帖子上的 cmets 数量。我什至不需要看 cmets 是什么。只是数量。谢谢!

【问题讨论】:

  • 我不确定您在这里寻找什么——推文没有“cmets”。你的意思是回复

标签: python python-3.x twitter tweepy


【解决方案1】:

我相信你的意思是回复。无论如何,您所要做的就是仔细检查页面源(CTRL+F 并搜索“回复”),这样您就可以知道稍后在 BeautifulSoup 对象中查找什么:

import requests
from bs4 import BeautifulSoup

html = requests.get('https://twitter.com/Cristiano/status/912028229011169281')
soup = BeautifulSoup(html.text, 'lxml')

comments = soup.find_all('span', attrs={'class':'ProfileTweet-actionCountForAria'})[0].contents

print(*comments)

...输出:

9,370 条回复

【讨论】:

  • 这不使用tweepy吗?
  • 不,它没有。问题是“有没有办法使用 python 获取推文上的 cmets 数量?”,没有提到 tweepy
  • 此方法使用网络抓取,违反了 Twitter 的规则和政策。您应该改用 Twitter API。但是,您需要使用 Search API 来查找和统计对推文的回复。
【解决方案2】:

不同版本的 Twitter API 及其对 tweepy 的支持

Twitter API 有 2 个不同的版本,v1.1 和 v2。 v1 不允许获取评论计数,只能转发和点赞。 v2 支持metrics 并允许。

Tweepy,当使用tweepy.API 时仅支持 v1。在编写此答案 [05/07] 时,当前对 v2 的支持位于 developmentTweepy features 与 v2 API 交互只能在 master 分支中用于开发目的。

Tweepy 使用 Twitter API v2

使用生产分支安装 tweepy:
pip install git+https://github.com/tweepy/tweepy.git

检索 cmets 的数量(和其他推文指标):

import tweepy

client = tweepy.Client(bearer_token="YOUR_BEARER_TOKEN")
client_result = client.get_tweet(1387426242060767234, \
      tweet_fields=["public_metrics"])
tweet = client_result.data

print(tweet.public_metrics["reply_count"])

附: : 由于功能正在开发中,可能会发生变化,应该更新帖子。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多