有什么方法可以使用 python 获取一条推文的评论数吗?

Is there any way to get the number of comments on a tweet using python?

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

我相信你的意思是回复。无论如何,您所要做的就是仔细检查页面源代码(CTRL+F 并搜索 "replies"),这样您就可以知道稍后在 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 replies

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

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

Tweepy,使用时 tweepy.API 仅支持 v1。在写这个答案 [05/07] 时,目前 development. Tweepy features 支持 v2 以与 v2 交互 API 仅在 master 分支中用于开发目的。

Tweepy 使用 Twitter API v2

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

检索评论数量(和其他推文指标):

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"])

P.S。 : 由于功能正在开发中,情况可能会发生变化,post 应该更新。